jQuery .prepend() using class from another element if it starts with specific word
I want to prepend using another existing elements class in the elements that will be prepended. For the sake of avoiding confusion lets say that i only know that the parent elements class has word "box" in the beginning and lets say rest of the class is randomly generated.
Therefore i obviously cant write for example:
.prepend('<div class="box-something_more"></div>');
Because for all i know, the parent elements class might be "box-nothing" or "box-something-else" or millions of other things.
html structure:
<div class="box-something"> <!-- source of the box- class -->
<div class="box-something_more"></div> <!-- prepended element -->
<div class="box-something_evenmore"></div> <!-- prepended element -->
</div>
<div class="box-two"> <!-- source of the box- class -->
<div class="box-two_more"></div> <!-- prepended element -->
<div c开发者_StackOverflow社区lass="box-two_evenmore"></div> <!-- prepended element -->
</div>
So what needs to happen is that the elements that will be prepended get the beginning of their class from the parent element.
http://jsfiddle.net/tDUpD/2/
Edit: this seems to do the trick. http://jsfiddle.net/tDUpD/3/
Does this do what you had in mind? If not, please try to state your question more clearly:
EXAMPLE:
HTML
<div class="foo"></div>
<div class="doo"></div>
JS
var childClasses = ["bar", "baz"];
$('.foo, .doo').each(function() {
var $self = $(this);
$.each(childClasses, function(i, childClass) {
$self.append($('<div/>', {
'class': $self.attr('class') + "_" + childClass
}));
});
});
= RESULTING HTML
<div class="foo">
<div class="foo_bar"></div>
<div class="foo_baz"></div>
</div>
<div class="doo">
<div class="doo_bar"></div>
<div class="doo_baz"></div>
</div>
精彩评论