Search code examples
javascriptgetelementsbyclassname

getElementsByClassName isn't returning all elements


I'm creating a button that I should highlight certain words within a specified class, but I am having issues with it returning all elements within the class. It will only work if I specify an index, so I'm assuming there may be something wrong with the existing "for loop". Any help is appreciated!

This will work, but only "highlights" the first element in the class, of course:

var bodyText = document.getElementsByClassName('test')[0].innerHTML;
for (var i = 0; i < searchArray.length; i++) {
bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, 
highlightEndTag);}

document.getElementsByClassName('test')[0].innerHTML = bodyText;  
return true;

This will not work at all:

var bodyText = document.getElementsByClassName('test').innerHTML;
for (var i = 0; i < searchArray.length; i++) {
bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, 
highlightEndTag);}

document.getElementsByClassName('test').innerHTML = bodyText;  
return true;

Solution

  • If you want to replace multiple words in multiple elements, you need two loops:

    const testElements = document.getElementsByClassName('test');
    for (const element of testElements) {
        for (const search of searchArray) {
            element.innerHTML = doHighlight(element.innerHTML, search, highlightStartTag, highlightEndTag);
        }
    }