Search code examples
javascriptjqueryloopsclassname

$(.class) only executes for the first tag of that class name


I am trying to make a javascript function that goes through the web page and looks for all of the tags of class name "option" and hides the ones that match the text in each of the if statements shown below.

In the example below, I tried using jquery to get the classes, but it only gets the first class with that name, not all of the classes of that name.

I have also tried using var element = document.getElementsByClassName('option'); to see if that would work but when I iterated through the list of elements and changed their display to none, the changes didn't show up.

What is a better way to iterate through a list of classes and update the css of only some of the elements?

Any help is appreciated. Thanks.

$(document).ready(function(){

if($('.option').html() == "C. "){
    $('.option').css('display','none');
}
if($('.option').html() == "D. "){
    $('.option').css('display','none');
}
if($('.option').html() == "E. "){
    $('.option').css('display','none');
}
if($('.option').html() == "F. "){
    $('.option').css('display','none');
}
});

Solution

  • You're not getting only one element, you just simply only manipulating the "first" element in the jQuery Object that is returned by the $('.option') call. What you need to is jQuery's .each() function in order to iterate through ALL of the elements returned by the jQuery call. Also, the long if statement can be shortened, but I assume you knew that and have other purposes. Anyway, once .each is called, you can use the callback function to manipulate EACH element as it is passed through. This is much like a for loop. The parameter i in the following example represents the index value of the element as the object is iterated through. It is 0 based, in other words, the 3rd option element to pass through would set the param i to 2

    Try this && Good Luck:

    $(function() {
        $(".option").each(function(i) {
            var txt = $(this).text();
            if (txt == "C." || txt == "D." || txt == "E." || txt == "F.")
                $(this).hide();
        });
    })
    

    Alternate links to investigate

    • .html()
      • Use this method to get or set the innerHtml of an element
    • .val()
      • Use this method to get or set the value of an element
        • Primarily HTML tags select, input, && textarea