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.
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).
$("#myid li"). click(function() { this.id = 'newId'; // longer method using . attr() $(this). attr('id', 'newId'); });
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.
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 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With