Reputation:
I'm trying to user jQuery to, for each element using the class button-0
, add a new child element with the class button-0-text
, and the text equal to the data-text
attribute of the original button-0
element. I tried this...
HTML:
<div class="flex fs-0 button-0" data-text="Enhance"></div>
Javascript:
$(".button-0").append($("<div></div>").addClass("button-0-text").text($(this).parent().attr("data-text")));
...but it's not working. Is this even the proper way to do it? Any help would be really appreciated. Thank you ^.^
Upvotes: 0
Views: 343
Reputation: 991
This should do it:
var buttons = $('.button-0');
buttons.each(function(i, elem){
var child = $('<div/>', {'class': 'button-0-text'});
child.text($(this).data('text'));
child.appendTo(this);
});
Upvotes: 0
Reputation: 1887
Try this way:
$('.button-0').each(function() {
$(this).append('<div class="button-0-text">' +$(this).data('text')+ '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flex fs-0 button-0" data-text="Enhance1"></div>
<div class="flex fs-0 button-0" data-text="Enhance2"></div>
Upvotes: 2