for the given html:
<div id="parent">
<div class="child">x</div>
<div class="child">y</div>
<div class="child">z</div>
</div>
How can I map the text of its children from an array?
This is my try:
var myArray = ['a', 'b', 'c'];
for (var i = -1; i < myArray.length; i++) {
$('#parent .child').each(function () {
$(this).text(myArray[i]);
});
}
I get: c,c,c
How can I get a,b,c
?
You don't need the outer for
loop:
var myArray = ['a', 'b', 'c'];
$('#parent .child').each(function (index) {
$(this).text(myArray[index]);
});
There's no need to use for
loop here.
var myArray = ['a', 'b', 'c']; $('#parent').find('div').each(function(){ $(this).html(myArray[$(this).index()]); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parent"> <div class="child">x</div> <div class="child">y</div> <div class="child">z</div> </div>
Use .text(function)
var myArray = ['a', 'b', 'c']; $("#parent > .child").text(function(index) { return myArray[index] })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <div id="parent"> <div class="child">x</div> <div class="child">y</div> <div class="child">z</div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.