Zeshan Munir
Zeshan Munir

Reputation: 1158

jQuery Advanced Selector for Multiple Elements

I am trying to add hidden class on two elements.

$("#grid").closest(".ui-jqgrid").addClass("hidden");
$("#grid").closest(".ui-jqgrid").prev("h3").addClass("hidden");

For the following markup,

<div class="col-sm-12">
    <h3>Heading 1</h3>
    <div class="ui-jqgrid  hidden" id="" dir="rtl" style="width: 1035px;">
        <div class="jqgrid-overlay ui-overlay" id=""></div>
        <div class="loading row" id="" style="display: none;"></div>
        <div class="ui-jqgrid-view" role="grid" id="">
            <div class="ui-jqgrid-titlebar ui-jqgrid-caption-rtl" style="display: none;">
                <a role="link" class="ui-jqgrid-titlebar-close HeaderButton " title="" style="left: 0px;">
                    <span class="ui-jqgrid-headlink glyphicon glyphicon-circle-arrow-up"></span></a>
                <span class="ui-jqgrid-title"></span>
            </div>

            <div class="ui-jqgrid-bdiv">
                <div style="position: relative;">
                    <div></div>
                    <table id="grid" class="ui-jqgrid-btable">
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

Can I do this in one line without finding the closest(".ui-jqgrid") twice? I don't want to add more classes to markup and also I don't want to use a JS variable here. Can anybody with strong selectors suggest a solution?

Upvotes: 0

Views: 462

Answers (2)

Jai
Jai

Reputation: 74738

You can do this:

$("#grid").closest('.col-sm-12').find(".ui-jqgrid, h3").addClass("hidden");

As you have the id of the grid #grid the traverse up at the wrapper element of all then use .find() method which can take multiple comma separated selectors then add the class on the found elements.

As per your comment you can change to this:

$("#grid").closest('[class^="col-sm"]')

Upvotes: 3

kapantzak
kapantzak

Reputation: 11750

Just chain the methods. jQuery returns the manipulated object every time you call a method, so you can just call the next method on the returned object.

This is known as chaining

$("#grid").closest(".ui-jqgrid").addClass("hidden").prev("h3").addClass("hidden");

Explanation

$("#grid")  // returns #grid
.closest(".ui-jqgrid")  // returns .ui-jqgrid 
.addClass("hidden")  // returns .ui-jqgrid
.prev("h3")  // returns the previous h3 element of .ui-jqgrid
.addClass("hidden");  // returns the h3

UPDATE (Chained and no need for new class)

// Select the closest '.ui-jqgrid', find its parent and hide it's direct children ('h3' and '.ui-jqgrid' div)
$('#grid').closest('.ui-jqgrid').parent().children().addClass('hidden');

Upvotes: 3

Related Questions