user208709
user208709

Reputation: 475

How to chain getElementById and getElementByClassName

I have a div with id "productPriceContainer" and within this div a class "price". I want to access the innerHTML of class "price" since I have other classes called "price" as well.

Can I chain something like this?

document.getElementById(productPriceContainer).getElementsByClassName(price).innerHTML

If not what is the correct way of doing what I need?

Thanks

Upvotes: 4

Views: 8589

Answers (3)

Moritz Roessler
Moritz Roessler

Reputation: 8611

  1. You are passing a variable, not a String to the method -> it should be "price" not price.

  2. The Method for retrieving Nodes by a classname is getElementsByClassName you were missing the "s"

  3. It returns an Array of DOM Elements so you have to iterate over the childs of your container

For example:

document.getElementById("productPriceContainer").getElementsByClassName("price")[0].innerHTML = "Asdf";

sets the innerHTML of the first DOM element with the class "price" within your container Element to "Asdf"

Iterating over the Elements could look like this:

var elements = document.getElementById("productPriceContainer")
if(elements) {
  var classes = elements.getElementsByClassName("price");
   for (var i = 0; i < elements.length; i++) {
     elements[i].innerHTML = "Asdf" + i;
    }
}

Here is a JSBin

Upvotes: 1

Quentin
Quentin

Reputation: 943220

Almost.

  • If you want to pass strings, then you have to pass strings and not undefined variables
  • getElementsByClassName (plural!) returns a NodeList, not a Node, so you have to loop over it to get the Nodes (on which you can then use innerHTML.

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382122

If you have one element with class price in the element with id productPriceContainer, you can do

 document.getElementById('productPriceContainer')
     .getElementsByClassName('price')[0].innerHTML

Notice the s in getElementsByClassName. It explains why you can't chain just like that. You don't have a function called getElementByClassName because, contrary to the id, there is no unicity of elements having a given class.

Upvotes: 6

Related Questions