Home > OS >  Why does my document.getElementsByClassName("obj").innerHTML doesn't work?
Why does my document.getElementsByClassName("obj").innerHTML doesn't work?

Time:10-04

I want to replace HTML in document with .innerHTML but for some reason it doesn't work:

HTML

<div class="specs">
    <div class="wrapp">
        <p class="line">Content</p>
    </div>
</div>

JS

document.getElementsByClassName("specs").innerHTML = "<p>Lorem ipsum</p>";

CodePudding user response:

getElementsByClassName returns a collection. Not a single item.

There are multiple ways to do this: You can run a for loop over the returned items.

let specs = document.getElementsByClassName("specs");
for(let i = 0 ; i < specs.length;i  ){
specs[i].innerHTML = "<p>Lorem ipsum</p>";
}

If you have only item, you can use querySelector which returns the first matched element.

document.querySelector(".specs").innerHTML = "<p>Lorem ipsum</p>";

CodePudding user response:

In a concise way this is how you'd do it

const targets = document.getElementsByClassName("specs")

if (targets.length)
  for (spec in targets)
    targets[spec].innerHTML = "<p>Lorem ipsum</p>";
<div class="specs">
  <div class="wrapp">
    <p class="line">Content</p>
  </div>
</div>

CodePudding user response:

I found your mistake.

document.getElementsByClassName returns an array of elements with the given class name. so try this.

document.getElementsByClassName("specs")[0].innerHTML = "<p>Lorem ipsum</p>";

For example if you have two elements with the same class name it returns an array containing both the elements, so you have to get the element using the specified index from the array.

  • Related