user3143218
user3143218

Reputation: 1816

JavaScript: Append To Multiple Classes

How can you append content to multiple classes using JavaScript?

This is what I'm working on:

<div class="element">
  <p>Existing Content</p>
  <p>Existing Content</p>
</div>

<div class="element">
  <p>Existing Content</p>
  <p>Existing Content</p>
</div>

After the function runs, the outcome should be the following:

<div class="element">
  <p>Existing Content</p>
  <p>Existing Content</p>
  <p>Added Content</p>
</div>

<div class="element">
  <p>Existing Content</p>
  <p>Existing Content</p>
  <p>Added Content</p>
</div>

This is my function so far (not working though):

var element = document.querySelectorAll('.element');

for (i = 0; i < element.length; ++i) {
element[i].innerHTML = element.innerHTML + '<p>Added Content</p>';
}

No jQuery Please :)

Upvotes: 1

Views: 464

Answers (1)

theftprevention
theftprevention

Reputation: 5213

You're missing the array index [i] in your innerHTML assignment. Instead of...

element[i].innerHTML = element.innerHTML + '<p>Added Content</p>';

...you should use:

element[i].innerHTML = element[i].innerHTML + '<p>Added Content</p>';

Upvotes: 9

Related Questions