I\'m trying to manipulate the HTML through getElementsByClass()
but for some reason it doesn\'t work. When I use document.getElementByID()
it works? Wh
Here's a widely supported solution:
function getElementsByClassName( root, clss ) {
var result = [], els, i;
if( arguments.length < 2 || !root || !clss || root.nodeType !== 1 ) {
return result;
}
clss = clss + '';
if( root.getElementsByClassName ) {
result = root.getElementsByClassName( clss );
} else if( root.querySelectorAll ) {
result = root.querySelectorAll( '.' + clss );
} else {
els = root.getElementsByTagName('*');
clss = " " + clss + " ";
for( i = 0; i < els.length; ++i ) {
if( ( " " + els[ i ].className + " " ).indexOf( clss ) !== -1 ) {
result.push( els[ i ] );
}
}
}
return result;
}
Then use it like this:
var bold = getElementsByClassName( document, "boldStuff" );
for( var i = 0; i < bold.length; ++i ) {
bold[ i ].innerHTML = 'Fred Flinstone';
}
The benefit to this is that it uses the native methods wherever possible.
It first tries getElementsByClassName
because it is generally fastest.
Then it tries querySelectorAll
, which will bring in support for IE8
.
Finally, it does a manual filtering of all elements under the provided root.
The correct method to call is getElementsByClassName()
, and it will give you an array of elements.
document.getElementsByClassName('boldStuff')
Anyway this is not compatible with older IE version. Check the compatibility here.
It returns an array so set the first element of the array's innerHTML
document.getElementsByClassName('boldStuff')[0].innerHTML = 'Fred Flinstone';
Try:
document.getElementsByClassName('boldStuff')[0]
getElementsByClassName
returns a NodeList. you will have to use
document.getElementsByClassName('boldStuff')[0].innerHTML
refer the docs at mdn