Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery select only first ul inside div

I have a ul in div. And I have another ul inside li. I need to select only first ul which located inside the div. How to achieve that in jquery.

The markup.

<div class="parent">
  <div class="clearfix">
    <div class="another-div">
      <ul class="first-ul">
        <li>First</li>
        <li>Second</li>
        <li>Third</li>
        <li>Fourth</li>
        <li>Fifth</li>
        <li>
          <ul class="second-ul">
            <li>First</li>
            <li>Second</li>
            <li>Third</li>
            <li>Fourth</li>
            <li>Fifth</li>
          </ul>        
        </li>
      </ul>
    </div>
  </div>
</div>

I want to select the first-li using only parent class. I have tried $('.parent > ul') but this is not working. and $('.parent ul') but this selects both ul. I don't want to use first-ul class or anything.

like image 466
Praveen Srinivasan Avatar asked Apr 09 '16 05:04

Praveen Srinivasan


People also ask

How do I get the first option selected in jQuery?

Select the <select> element using JQuery selector. This selector is more specific and selecting the first element using option:nth-child(1). This will get access to the first element (Index starts with 1).

How can get Li tag value in jQuery?

$("#myid li"). click(function() { this.id = 'newId'; // longer method using . attr() $(this). attr('id', 'newId'); });

What is first child in jQuery?

Definition and Usage. The :first-child selector selects all elements that are the first child of their parent. Tip: Use the :last-child selector to select elements that are the last child of their parent.


2 Answers

You can access the first ul in the following way also:

$('.parent ul:first li:first').css('color', 'blue');

ul:first will select the first ul in div with class as parent

Check this jsfiddle.

like image 127
Shubham Khatri Avatar answered Oct 31 '22 05:10

Shubham Khatri


Like this:

$("div > ul").addClass('selected');
ul:not(.selected) {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <div class="clearfix">
    <div class="another-div">
      <ul class="first-ul">
        <li>First</li>
        <li>Second</li>
        <li>Third</li>
        <li>Fourth</li>
        <li>Fifth</li>
        <li>
          <ul class="second-ul">
            <li>First</li>
            <li>Second</li>
            <li>Third</li>
            <li>Fourth</li>
            <li>Fifth</li>
          </ul>        
        </li>
      </ul>
    </div>
  </div>
</div>
like image 45
Pedram Avatar answered Oct 31 '22 05:10

Pedram