views:

37

answers:

4

This little search example works but only the first time.

How do I clear all the classes from the p elements so when searching the second time, the highlight from the previous search doesn't show?

<!DOCTYPE html>
<html>
    <head>
        <script src="http://www.google.com/jsapi" type="text/javascript"></script>
        <script type="text/javascript">
            google.load('jquery', '1.4.2');
            google.setOnLoadCallback(function() {
                $('#searchButton').click(function() {

                 //remove all added classes so we can search again
                 //jQuery.each($('p'), function() {
                    //$('#' + this).addClass('');
                 //}

                 $('p:contains("' + $('#searchText').val() + '")').addClass('highlight');
                });
            });
        </script>
        <style>
            p.highlight {
                background-color: orange;
            }
        </style>
    </head>
    <body>
        <input id="searchText" value="second" />
        <button id="searchButton">Search</button>
        <p>This is the first entry.</p>
        <p>This is the second entry.</p>
        <p>This is the third entry.</p>
        <p>This is the fourth entry.</p>
    </body>
</html>
A: 

Use removeClass() to remove the class, then search again and add the class to the new matches. While I'm at it, I'll use filter() to search the selection of <p> elements that was just made with $('p') instead of doing another $(...) call:

$('#searchButton').click(function() {
    $('p')
        .removeClass('highlight')
        .filter(':contains("' + $('#searchText').val() + '")')
        .addClass('highlight');
});
BoltClock
A: 

Use removeClass

$('p').removeClass('highlight') will remove just the highlight class from the previous search $('p').removeClass() will remove all classes from all p's

Adam
+2  A: 

You can remove the highlight class on all the p then do hightlight again on matched elements.

$('p').removeClass('hightlight');
Teja Kantamneni
+1  A: 

If you want to remove ALL classes, you can use removeAttr on class, or set class to "". So...

$('#searchButton').bind('click',function(){
  $('p').removeAttr('class');
  <!-- OR -->
  $('p').attr('class','');
});

Using "each()" isn't necessary because jQuery will automatically perform these actions on all elements within the collection.

RussellUresti