Search code examples
javascriptcssstylesheet

How to change css styles based on element contents with Javascript


Within the following code, I would like to hide any li tags that do not contain specific content. For example, hide any li tags that do not contain "ALL" or "LOGO" text content, as shown below.

<ul>
    <li class="filterTag">
        <span><a href="~">ALL</a></span>
    </li>
    <li class="filterTag">
        <span><a href="~">GUIDES</a></span>
    </li>
    <li class="filterTag">
        <span><a href="~">LOGO</a></span>
    </li>
    <li class="filterTag">
        <span><a href="~">ICON</a></span>
    </li>
 </ul>

I know that the following css hides the li:

<li style="display:none;">

However, I’m hoping someone can help with the Javascript function that searches the contents of the li, finds the matching values, then converts class="filterTag" to style="display:none;".

The following JS code doesn’t work for me, however, it is sourced from another example and not sure if all code is needed:

var listLi=document.getElementsByTagName("li").getElementsByClassName('filterTag');
for(var i=0;i<listLi.length;i++) {
    var listLink = listLi[i].getElementsByTagName("a");
    for(var j=0;i<listLink .length;i++) {
        if(listLink [j].innerHTML!==('ALL' || 'LOGO'))
            listLink [j].style.display="none";
    }
}

Note that I have also added the extra filter:

.getElementsByClassName('filterTag') as there are other li's on the page.

Note sure if I need to add the extra:

.getElementsByTagName("a");?


Solution

  • It is always good to separate styles in CSS instead of writing inline styles. So just add a class (in this case fancy, change to your needs) For illustrating purposes instead of hiding I've added a background-color: orange;

    Please read the comments in code carefully

    var needles = ["ALL", "LOGO"]; // define the needles you need to find
    var filterTags = document.querySelectorAll('.filterTag'); // get all filterTags
    filterTags.forEach(function(filterTag){ // iterate over all filterTags
        if(needles.includes(filterTag.textContent.trim())) { // here the magic happens:
            // it compares if filterTag content is in the array of needles
            // if so we add the class name fancy 
            filterTag.classList.add('fancy');
            // instead of the above line you could do:
            // filterTag.style.display = "none";
        }
    });
    .fancy {
        /* change the style to display none instead of background-color */
        /* display: none; */
        background-color: orange;
    }
    <ul>
        <li class="filterTag">
            <span><a href="~">ALL</a></span>
        </li>
        <li class="filterTag">
            <span><a href="~">GUIDES</a></span>
        </li>
        <li class="filterTag">
            <span><a href="~">LOGO</a></span>
        </li>
        <li class="filterTag">
            <span><a href="~">ICON</a></span>
        </li>
     </ul>