Reputation: 475
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
Reputation: 8611
You are passing a variable, not a String to the method -> it should be "price"
not price
.
The Method for retrieving Nodes by a classname is getElementsByClassName
you were missing the "s"
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
Reputation: 943220
Almost.
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
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