You can do it like this:
var list = document.getElementById("foo").getElementsByClassName("bar");
if (list && list.length > 0) {
list[0].innerHTML = "Goodbye world!";
}
or, if you want to do it with with less error checking and more brevity, it can be done in one line like this:
document.getElementById("foo").getElementsByClassName("bar")[0].innerHTML = "Goodbye world!";
In explanation:
- You get the element with
id="foo"
.
- You then find the objects that are contained within that object that have
class="bar"
.
- That returns an array-like nodeList, so you reference the first item in that nodeList
- You can then set the
innerHTML
of that item to change its contents.
Caveats: some older browsers don't support getElementsByClassName
(e.g. older versions of IE). That function can be shimmed into place if missing.
This is where I recommend using a library that has built-in CSS3 selector support rather than worrying about browser compatibility yourself (let someone else do all the work). If you want just a library to do that, then Sizzle will work great. In Sizzle, this would be be done like this:
Sizzle("#foo .bar")[0].innerHTML = "Goodbye world!";
jQuery has the Sizzle library built-in and in jQuery, this would be:
$("#foo .bar").html("Goodbye world!");
document.getElementsByClassName
would work fine. – Pindus