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

89
Views
Looping through html div with javascript and changing the inner html of each div
<!DOCTYPE html>
<html style="background-color: #D1D1D1 ">

<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="./main.css" />
</head>
<body id="body">

    <h1 id="headerTitle"></h1>

    <div>
        <p id="header">November 29th</p>
    </div>

    <div>
        <p id="header">November 29th</p>
    </div>

    <div>
        <p id="header">November 29th</p>
    </div>

    <script src="./main.js"></script>
</body>
</html>

I'm trying to loop through the body and get into each div and change the November 29th text. The closest i've gotten is with this:

var body = document.getElementsByTagName("div")

for (i = 0; i < body.length; i++) {
    document.getElementById("header").innerHTML = "Hello World!";
}

but it only changes the first div and stops.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

It is only changing the first div since an id is only supposed to belong to one element so it stops after it finds that element. Change the id field on the p tags to class and you could use

let body = document.getElementsByClassName()
for (let element of body) {
    element.innerHTML = "..."
}
about 4 years ago · Juan Pablo Isaza Report

0

As already mentioned, you shouldn't have more than 1 element with the same id. Changing the ids to class, this code should work:

[...document.querySelectorAll('.header')].map((elem) => elem.textContent = 'Hello World!');
about 4 years ago · Juan Pablo Isaza Report

0

//Just to change the data in the div's u can do this

var div_s = document.getElementsByTagName("div")

    for (i = 0; i < div_s.length; i++) {
        div_s[i].innerHTML = "Hello World!";
    }

OR to change the data in p's u need unique id's for each tag such as given below.

<div title = "header1">
    <p id="header1">November 29th</p>
</div>

<div title = "header2">
    <p id="header2">November 29th</p>
</div>

<div title="header3">
    <p id="header3">November 29th</p>
</div>
<script>
    var divs = document.getElementsByTagName('div')

    for (i = 0; i < divs.length; i++) {
        document.getElementById(divs[i].title).innerHTML = "Hello World!";
    }
</script>
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!