0

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 ?

3 Answers 3

5

You don't need the outer for loop:

var myArray = ['a', 'b', 'c'];

$('#parent .child').each(function (index) {
    $(this).text(myArray[index]);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I appreciate it!
2

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>

6 Comments

each already provides an optional parameter for the callback which is the index!
@ibrahimmahrir I have seen it inside florian's answer. It's just an another way to solve it. And by the way - in would be unfair if I would copy&paste florian's solution.
If a better answer is already provodided then you could just step down and not answering!
@ibrahimmahrir I just wonder - have you to use ! in your every sentence? Anyways, it's just less 'elegant' solution, not worse.
I didn't say worse! It's still a correct answer and a better way but not the best!!!!!!!!!!!!
|
2

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>

2 Comments

Thank you! I appreciate it!
@null Note, .each() is not necessary to return expected result. First parameter of .text(function(index, existingText){}) callback is index of current element in jQuery() collection. .text() iterates each element in the collection returned by $("#parent > .child") call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.