Home > Software engineering >  Looping through html div with javascript and changing the inner html of each div
Looping through html div with javascript and changing the inner html of each div

Time:11-30

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

CodePudding user response:

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 = "..."
}

CodePudding user response:

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!');

CodePudding user response:

//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>
  • Related