3

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

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Gary Voss
  • 225
  • 3
  • 13

3 Answers3

5

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

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

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

Ajay Gaur
  • 5,140
  • 6
  • 38
  • 60
0

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>
Oriol
  • 274,082
  • 63
  • 437
  • 513