Gary Voss
Gary Voss

Reputation: 235

Adding a child element to all divs of the same class

I'm attempting to add a child span to all div's with the same class.

I can achieve this to a individual element by targeting its Id

HTML

<div id="h1" class="header">Hello </div>
<hr>
<div id="h2" class="header">what about this one </div>

JavaScript

var header = document.getElementById('h1');

var newSpan = document.createElement("span");
header.appendChild(newSpan);
newSpan.innerHTML = "i'm here";

However when I change it to

var header = document.getElementsByClassName('header');

It fails to work.

Can anyone see where I'm going wrong?

JSFiddle

Upvotes: 3

Views: 2363

Answers (3)

Oriol
Oriol

Reputation: 288010

You can consider inserting the text as CSS generated content:

.header::after {
  content: "i'm here";
}
<div id="h1" class="header">Hello </div>
<hr />
<div id="h2" class="header">what about this one </div>

Upvotes: 0

Ajay Gaur
Ajay Gaur

Reputation: 5270

The javascript document.getElementById will return only one Id, but document.getElementByClassName will return a collection of array-like objects and it should be used here.

I have updated your js code to :

var header = document.getElementsByClassName('header');
//console.log(header);

for(var i=0;i<header.length;i++){
    var newSpan = document.createElement("span");
    header[i].appendChild(newSpan);
    newSpan.innerHTML = "i'm here";
}

and HTML code to :

<div id="h1" class="header">Hello </div>
<hr>  
<div id="h2" class="header">what about this one </div>

HTML code had some slight mistake of class"header" instead class="header"

Fiddle

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115212

To do that you need to iterate over them, since getElementsByClassName() returns an array like html element collection. You can use for loop

var headers = document.getElementsByClassName('header');

for (var i = 0; i < headers.length; i++) {
  var newSpan = document.createElement("span");
  newSpan.innerHTML = "i'm here";
  headers[i].appendChild(newSpan);
}
<div id="h1" class="header">Hello</div>
<hr>
<div id="h2" class="header">what about this one</div>

or you can use Array.prototype.forEach with call() to iterate over it

var headers = document.getElementsByClassName('header');

[].forEach.call(headers,function(ele) {
  var newSpan = document.createElement("span");
  newSpan.innerHTML = "i'm here";
  ele.appendChild(newSpan);
})
<div id="h1" class="header">Hello</div>
<hr>
<div id="h2" class="header">what about this one</div>

For more about iteration check :- For loop for HTMLCollection elements

Upvotes: 5

Related Questions