Vaibhav Jain
Vaibhav Jain

Reputation: 34407

jQuery Selector for all descendants of a element

I have a <div id="rptViewer"> that has multiple div and tables, which in turn can have multiple div and tables. I need a jQuery selector to select all the div or tables under "rptViewer" either directly or indirectly(nesting).

I am trying the following jQuery selectors.

<script type="text/javascript">
    $(document).ready(function() {
        $("[id*='rptViewer'] table").each(function(i, item) {
             $(item).css('display', 'inline-block');
            });
            $("[id*='rptViewer'] div").each(function(i, item) {
                $(item).css('display', 'inline-block');
            });            

            $("[id*=rptViewer] table").attr("width","");
        });
    </script>

But when I am checking it using firebug, I found that only the direct child of 'rptViewer' are getting 'inline-block' CSS

Upvotes: 1

Views: 5101

Answers (2)

maxcnunes
maxcnunes

Reputation: 3027

If you would like to include a class for all table and div inside of rptViewer. You can do this way:

$("table, div", "#rptViewer").addClass('someStyle');

But if you would like to include a class only for real children of rptViewer. You can do this way:

$("#rptViewer > table, #rptViewer > div").addClass('someStyle');

Upvotes: 4

zzzzBov
zzzzBov

Reputation: 179046

Instead of adding styles in JavaScript, add a style via CSS:

#rptViewer div,
#rptViewer table {
  display: inline-block;
}

You can use the [id] selector, and a comma separated list of selections:

$('#rptViewer div, #rptViewer table')...

If there are more elements you'd like to select, you might want to use .find():

$('#rptViewer').find('div, table')...

Given that you're using rptViewer as an [id], I'm going to assume you're using ASP.NET, in which case you should add a class to the element to simplify selection:

$('.viewer').find('div, table')...

Upvotes: 2

Related Questions