ultraloveninja
ultraloveninja

Reputation: 2139

Append string to elements having same class name

Not sure what I need to change up, but I have two elements in separate div's with the same class name and I'm not sure how I can populate both of them.

HTML:

<div>
  <a class="this-thing">Text</a>
</div>
<div>
  <a class="this-thing">Text</a>
</div>

JS

const text = document.querySelectorAll(".this-thing");
text.innerHTML +='Add'

Not sure why it would work when I have one instance, but then if I add another element with the class this-thing it doesn't work at all.

Upvotes: 1

Views: 1448

Answers (4)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

Element.getElementsByClassName() is usually much faster than .querySelectorAll() (and reads more naturally), so I would recommend to use the former.

Also, Node.textContent would be better (both faster and safer) option to modify inner text of the node, so your line may be as simple, as:

[...document.getElementsByClassName('this-thing')].forEach(node => node.textContent += ' Add')

Following is the quick demo:

[...document.getElementsByClassName('this-thing')].forEach(node => node.textContent += ' Add')
<div><div class="this-thing">Some text</div></div><div><div class="this-thing">Some other text</div></div>

Upvotes: 5

Seif El-Din Sweilam
Seif El-Din Sweilam

Reputation: 274

Loop into the results of querySelectorAll() :

var texts = document.querySelectorAll(".this-thing");
for (let text in texts) {
    text.innerHTML += 'Add';
}

This is because the return value of querySelectorAll() isn't a single object, but a NodeList of objects as mentioned in the documentations in the Return value section.

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

Return Value

A non-live NodeList containing one Element object for each element that matches at least one of the specified selectors or an empty NodeList in case of no matches.

Upvotes: 0

thingEvery
thingEvery

Reputation: 3434

querySelectorAll() returns a NodeList of elements. So you'll need to loop through them and add the text to each one.

const text = document.querySelectorAll(".this-thing");
text.forEach(element => element.innerHTML += ' Add');
<div>
  <a class="this-thing">Text</a>
</div>
<div>
  <a class="this-thing">Text</a>
</div>

Upvotes: 1

Benny Powers
Benny Powers

Reputation: 5836

Try this

document.querySelectorAll(".this-thing").forEach(element => {
  element.innerHTML +='Add'
});

Upvotes: 1

Related Questions