Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • jQuery methods to select elements by hierarchy

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 310
    Comment on it

    Selecting elements in a hierarchy is very useful when the HTML is very nested and the unique id or class is not associated with every element. In such a cases, we first select that element that has some unique id or class and then move to the desired element step by step.


    Suppose we have the following HTML


    <div class="techQuery" style="float:left;">
     <p>Keep the recording private and share the link or make it public.</p>
      <li>Type in your tech analysis, product insights and tech solutions.</li>
      <li>Record your Desktop for better insights.</li>
      <li>The recording is saved on cloud.</li>
      <li>Share the link.</li>


    If we have to select the direct descendant or child of any element then we use '>' symbol


    $("div.techQuery > ul > li")


    This will select all the 'li' elements present under ".techQuery" class.


    In the above jQuery we have specified every step to 'li' tag from 'div' tag but if we want all 'li' under the ".techQuery" class ie anywhere below this element then we will not use '>' symbol.


    $("div.techQuery li")


    Suppose, we want to select that element that immediately follows some other element and both the elements are the child of same parent then we can achieve this with the help of '+' symbol.


    $("div.techQuery p+ul")


    This will select only those elements that have <ul> tag immediately after <p> tag.


    If there is a list and we have a requirement to select the first child or the last child or the child present at any specified position then we can achieve this in the following manner:


    $("div.techQuery li:first-child")
    $("div.techQuery li:last-child")
    $("div.techQuery li:nth-child(2)")


    The first jQuery will select only the first <li> child ie "Type in your tech analysis, product insights and tech solutions"


    The second jQuery will select the last <li> ie "Share the link"


    The last jQuery will select the second <li> ie "Record your Desktop for better insights"

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: