-5

Why this code is not working ? I think i am doing some silly mistake here.

document.addEventListener("DOMContentLoaded", function() {
  var text = "Planing";
  document.getElementsByTagName("div").innerHTML = text;
});
<div id="demo" class="eg"></div>
Tushar
  • 85,780
  • 21
  • 159
  • 179
akash
  • 2,117
  • 4
  • 21
  • 32

2 Answers2

4

getElementsByTagName returns a collection of all the matching elements(<div>s in this case) on the page/DOM, to select first element use array notation with zero index.

document.addEventListener("DOMContentLoaded", function() {
  var text = "Planing";
  document.getElementsByTagName("div")[0].innerHTML = text;
});
<div id="demo" class="eg"></div>

If you want to select first element, you can use document.querySelector('div');

If you want to perform some operation on all the selected elements, you need to iterate over them.

var allDivs = document.getElementsByTagName("div");

for (var i = 0; i < allDivs.length; i++) {
    allDivs[i].innerHTML = 'Div ' + i;
}
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • 1
    @akash Check updated fiddle, https://jsfiddle.net/tusharj/ushqasq7/2/, this is because how jsfiddle includes script in page, I've selected the option to `no wrap`, if you select it to `onLoad` or `contentLoaded` the script is added inside the respective handler – Tushar Oct 09 '15 at 15:04
  • 1
    @akash For more information on how it works on jsfiddle please see bottom part http://stackoverflow.com/a/32925927/2025923 – Tushar Oct 09 '15 at 15:07
2

getElementsByTagName, as the name suggests returns an array of elements (even if there is just one). You need to access the first one before applying the text.

document.addEventListener("DOMContentLoaded", function() {
  var text = "Planing";
  document.getElementsByTagName("div")[0].innerHTML = text;
});
<div id="demo" class="eg"></div>
Tushar
  • 85,780
  • 21
  • 159
  • 179
Matheus208
  • 1,289
  • 2
  • 13
  • 26
  • I didn't copy and paste. I clicked on "copy snippet to answer" from OP's question and fixed it... I just realised now, after refreshing the page, that someone else beat me to posting another answer first. – Matheus208 Oct 09 '15 at 14:59