Edward Tanguay
Edward Tanguay

Reputation: 193362

How do I remove all classes from a collection of $('p')?

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>

Upvotes: 0

Views: 129

Answers (4)

RussellUresti
RussellUresti

Reputation: 6221

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.

Upvotes: 1

BoltClock
BoltClock

Reputation: 724222

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');
});

Upvotes: 0

Teja Kantamneni
Teja Kantamneni

Reputation: 17472

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

$('p').removeClass('hightlight');

Upvotes: 2

Adam
Adam

Reputation: 44949

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

Upvotes: 0

Related Questions