0

I have a unordered list in my html document where am trying to update each of the list elements of which there are five with text from an ajax request. Here is a snippet of my code:

var modify = document.getElementsByTagName('li');
var modifyText = document.createTextNode( request.responseText );
var modifiedElements = [].slice.call(modify);
modifiedElements.forEach(function(elem){
    console.log(elem);
    elem.appendChild(modifyText);
});

The problem i am having is that only the last list element is being updated. Why is that the case? Thank you.

1
  • if you are sure no other content is in there you can use elem.innerHTML = request.responseText; Commented Feb 16, 2016 at 7:42

2 Answers 2

3

You are creating only 1 text node, which is placed in each li element, resulting in moving it from the previous node.

You need to create a new node for each iteration

var request = {
  responseText: 'some text'
}; //as a stub
var modify = document.getElementsByTagName('li');
[].forEach.call(modify, function(elem) {
  var modifyText = document.createTextNode(request.responseText);
  console.log(elem);
  elem.appendChild(modifyText);
});
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

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

4 Comments

Is [] == Array.prototype ?
the result example html should contain the string 'some text'
no... it is a empty array... just shortcut for using Array.prototype.forEach() - we create an empty array and access the forEach method
it is but if the html you posted is the result it should contain the text some text in all the li's
1

About Node.appendChild() method:

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position. ... So if the node already has a parent, the node is first removed, then appended at the new position. The Node.cloneNode() can be used to make a copy of the node before appending it under the new parent

In such case you can use Node.cloneNode() method:

var modify = document.getElementsByTagName('li');
var modifyText = document.createTextNode( request.responseText );
var modifiedElements = [].slice.call(modify);
modifiedElements.forEach(function(elem){
    console.log(elem);
    elem.appendChild(modifyText.cloneNode());
});

https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode

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.