Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
Why does my document.getElementsByClassName("obj").innerHTML doesn't work?

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>";
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>";
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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. 👍

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!