1

I have problem with weird behaviour in JavaScript that I don't understand:

If I get element (for example a row in table) like this:

var someElement = document.getElementById("row1");

And then try to find element by class from that element (column for example) and change the innerHTML, nothing happens:

someElement.getElementsByClassName("column1").innerHTML = "new text";

But if I instead do this:

someElement.childNodes[0].innerHTML= "new text";

The elements innerHTML changes and is visible on the DOM. Why is this happening like this? I think the class thing would produce cleaner code for me right now, so is there a way to get the class method to work as I think it should?

I'm using the newest version of Chrome.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Nyxeria
  • 363
  • 1
  • 4
  • 12

2 Answers2

2

There is no getElementByClassName() should be getElementsByClassName() (note the s at the end of elements.

But the main problem come's when you're trying to call the property of object innerHTML on the result of getElementsByClassName() that return an array-like object of all child elements which have all of the given class names.

Anyway I suggest the use of querySelector() or querySelectorAll() instead like :

someElement.querySelector(".column1").innerHTML = "new text";
//Or
someElement.querySelectorAll(".column1")[0].innerHTML = "new text";

Else you could just point on the first element of the returned result like :

someElement.getElementsByClassName("column1")[0].innerHTML = "new text";
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

Thing is ID is unique, Class can be used on multiple elements that is why function is called getElementsByClassName, notice the S in elements, to change anything with class you must go through loop, so you can use this for example

    var a = document.getElementsByClassName("example"); 

    for( let i = 0; i< a.length;i++)
         a[i].style.top = "50px";

Notice: this is only example, use your innerhtml or whatever you need instead

Armin
  • 373
  • 2
  • 13