2

How can I do this same functionality to es6? I'm trying to add this text to the list item

var names = [ "Jon", "Nick", "Bill", "Tom" ];

$('#names-list li').each(function (index) {
 $(this).text(names[index]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="names-list">
 <li></li>
 <li></li>
 <li></li>
 <li></li>
</ul>

2
  • "How can I do this same functionality to es6?" Exactly the same. What's your point? Commented Oct 19, 2017 at 8:26
  • Did you mean "How do I do this without jQuery?" This question seems not so connected to ES6 per se. Commented Oct 19, 2017 at 8:28

2 Answers 2

7

ES6 seems unrelated to what you're asking.

The gist of your question seems to be 'how do I achieve this without jQuery?'. In which case the equivalent would be to use querySelectorAll() to get the li elements, forEach() to loop over them and then set the textContent, like this:

var names = ["Jon", "Nick", "Bill", "Tom"];

document.querySelectorAll('#names-list li').forEach(function(li, index) {
  li.textContent = names[index];
});
<ul id="names-list">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

Sign up to request clarification or add additional context in comments.

10 Comments

ES6 and querySelectorAll are not really connected.
Perhaps, but I think the theme of the OP is 'how do I do this without jQuery'. I removed the reference to ES6 to save confusion.
I know - hence my previous comment about reading between the lines and saying the OP is asking how to have the same logic without jQuery.
I think jQuery text() method is more like setting textContent rather than innerText which will trigger a reflow and some other bad things.
@Kaiido I checked the source, you're correct. I updated the answer. Thanks.
|
0

If you're looking for 100% ES6, here you go:

const names = ["Jon", "Nick", "Bill", "Tom"];

const namesList = document.querySelectorAll("#names-list li");

for (let i in namesList) {
  namesList[i].innerText = names[i];
};

But I wouldn't really write the code like this if I were given any coding style.

Comments

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.