jQuery select elements on 1st "level"

44,329

Solution 1

$("#BaseElement").children("span");

or

$("#BaseElement > span");

See jQuery selectors and children().

Solution 2

In the jQuery API, when it refers to 'descendants' it means all levels, and when it refers to 'children' it means only the first level

this will get you all first level children (in your example the first p, div, 2 spans, and last p)

$('#BaseElement > *')

Solution 3

Also refer to What is the difference direct descendent (>) vs. descendant in jQuery selectors? for differences between space and > in selectors. With space equals to find() and > equals to children(). In other words, the following pairs are equivalent,

$("#BaseElement").children("span");
$("#BaseElement > span");

Get all children plus their descendants:

$("#BaseElement").find("span");
$("#BaseElement span");
Share:
44,329
Admin
Author by

Admin

Updated on July 21, 2020

Comments

  • Admin
    Admin almost 4 years

    I want to select only the elements on the first "level".

    Ex:

    <div id="BaseElement">
      <p>My paragraph 0</p>
      <div>
        <span>My Span 0</span>
        <span>My Span 1</span>
      </div>
      <span>MySpan 2</span>
      <span>MySpan 3</span>
      <p>My paragraph 1</p>
    </div>
    

    Let's say that you got the BaseElement node.

    var Element = $("div#BaseElement");
    

    How do I fetch nodes from only the base element node?

    $("div#BaseElement span")
    

    should only result in getting MySpan 2 and MySpan 3.