-1

I have a list of HTML article tags that are dynamically generated. Some of the article tags have a class named "featured". I want to insert some HTML right before the closing article tag where the class is named "featured" using plain javascript.

<article class="list-item featured">
  ....
</article>

<article class="list-item">
  ....
</article>

<article class="list-item featured">
  ....
</article>

<article class="list-item">
  ....
</article>

I tried using something like, but it did not work. I got an error: featuredItem.insertAdjacentHTML is not a function. What syntax should I be using to do this?

  var featuredItem = document.getElementsByClassName("featured");
  featuredItem.insertAdjacentHTML('beforeend','<div class="ribbon-featured"></div>');
user1669296
  • 425
  • 1
  • 6
  • 13

2 Answers2

0

getElementsByClassName returns an array-like object containing 0 or more elements. You can't invoke insertAdjacentHTML on the set of returned elements, you need to pick one element from the set to manipulate its content.

user229044
  • 232,980
  • 40
  • 330
  • 338
0

getElementsByClassName returns an array-like object, so you can forEach through each array object with the featured class name as such:

document.getElementsByClassName("featured").forEach(featuredItem => {
  featuredItem.insertAdjacentHTML('beforeend','<div class="ribbon-featured"></div>')
})
ReyHaynes
  • 2,932
  • 1
  • 15
  • 22