treehouse : what would you like to learn today?
Web Design Web Development iOS Development

How to use jQuery to parse all the classes with name/ID of?

  • I have some dynamic content that gets published in a <span> of ID "giftopt". There can be any number of these <span> tags with ID = "giftopt". Is there a way with jQuery to check the text in ALL the <span></span> tags with ID = "giftopt" until it finds the word I am looking for or doesn't at all?

    I would like to write a conditional statement that:


    <script type=\"text/javascript\">
    jQuery.noConflict();
    jQuery(document).ready(function(){
    jQuery(\".warning\").hide()

    var giftopt = jQuery(\"#giftopt\").text();
    if (giftopt == 'Someone Else') {
    jQuery(\".warning\").show('slow');
    }

    });

    </script>


    My inital test seems that it will check until it comes to the first class with ID "giftopt", but it is highly likely that the first one won't have the text I am looking forward and I need it to continue to see if there is any other classes with ID = "giftopt".

    Any help?
  • ID's are UNIQUE, especially when it comes to JavaScript. You'll need to use a CLASS name of "giftopt" if there are going to multiples on the page that you need to target all as a group.
  • Thats fine.

    So I use a class...

    How do I parse them all to see if any of them contain a certain text?
  • No one knows how?
  • to see if a span contains something you can check with a $('span:contains(the word you are looking for)')

    a simple example would be

    $(document).ready(function() {

    $('span:contains(the word you are looking for)').do what you want from here('');

    });
  • Thanks Pab.

    Is this going to check "ALL" Span's" tags on the page or just the first one it finds as in my experience (my the cord I included)?