1

I am trying to use JavaScript to change the text of this element. However it is not working. Here is the header im trying to change - enter image description here

var elem = document.getElementsByClassName("headertext");
elem.innerHTML = "hello world";
<ul class="headertable">
  <li>
    <p class="headertext">Home</p>
  </li>
  <li>
    <p class="headertext">About US</p>
  </li>
  <li>
    <p class="headertext">Contact US</p>
  </li>
</ul>
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73
Zeronir
  • 67
  • 5

1 Answers1

3

document.getElementsByClassName returns an array-like object of all child elements which have all of the given class name(s).

Here the elem will be an HTMLCollection. So elem.innerHTML is not valid.

So you should use the index to update the required node

like elem[0].innerHTML or elem[1].innerHTML or elem[2].innerHTML

var elem = document.getElementsByClassName("headertext");
elem[0].innerHTML = "hello world";
elem[1].innerHTML = "hello world 1";
elem[2].innerHTML = "hello world 2";
<ul class="headertable">
    <li><p class="headertext">Home</p></li>
    <li><p class="headertext">About US</p></li>
    <li><p class="headertext">Contact US</p></li>
</ul>
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
  • This is still not changing my elements on my browser? – Zeronir Jan 31 '22 at 12:06
  • @Zeronir That code should work in all popular modern browsers. Do you run your code with a [DOMContentLoaded](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event) event handeler? – Mark Baijens Jan 31 '22 at 12:09
  • 1
    Please ensure that your script tag is below your element. So that the script can access your dom elements. https://stackoverflow.com/questions/9899372/pure-javascript-equivalent-of-jquerys-ready-how-to-call-a-function-when-t – Nitheesh Jan 31 '22 at 12:10
  • @Zeronir the example given here works fine for me. If that is the case for you as well, but it does not work when you try it within your site - well then we need a _proper_ problem description from your first of all. You need to provide a proper [mre] of your issue in such cases. – CBroe Jan 31 '22 at 12:10
  • 1
    SO fiddle places the script snippet below its body tag so that the script can asscess the elements inside template. Your template should be something like this
    Your Template
    – Nitheesh Jan 31 '22 at 12:12
  • 1
    @Nitheesh Yes it works now. My script tag was within the head tag. Thanks a lot. – Zeronir Jan 31 '22 at 12:15