Reputation: 410
I have following html code
<div style="column-count: 3;">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
It divides the ul's into three columns. Now i want to get all the elements of first column only using JQuery. Is this possible ??
Upvotes: 0
Views: 466
Reputation: 2148
You can get all first li
value by this:
$("div ul").each(function(t){ alert( $(this).find("li:first").text() ); } );
similarly you can use nth-child
also..
$("div ul").each(function()
{
$("#sa").text( $("#sa").text() + " > " +
$(this).find("li:first").text();
//$(this).find("li:nth-child(1)").text();
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div style="column-count: 3;">
<ul>
<li>1.1</li>
<li>1.2</li>
<li>1.3</li>
<li>1.4</li>
</ul>
<ul>
<li>2.1</li>
<li>2.2</li>
<li>2.3</li>
<li>2.4</li>
</ul>
<ul>
<li>3.1</li>
<li>3.2</li>
<li>3.3</li>
<li>3.4</li>
</ul>
</div>
<span id="sa"></span>
Upvotes: 0
Reputation: 303
<div>
<ul>
<li>John</li>
<li>Karl</li>
<li>Brandon</li>
</ul>
</div>
<div>
<ul>
<li>Sam</li>
</ul>
</div>
<div>
<ul>
<li>Glen</li>
<li>Tane</li>
<li>Ralph</li>
<li>David</li>
</ul>
</div>
<script>
$( "ul li:nth-child(2)" ).append( "<span> - 2nd!</span>" );
</script>
https://api.jquery.com/nth-child-selector/
Upvotes: 0
Reputation: 5560
use the :nth-child() selector
$( "ul:nth-child(1) li:nth-child(2)" )
will selects the second li
of the first ul
Upvotes: 0
Reputation: 6795
To get the li
's of the first ul
then you can do:
$('ul:first-child').find('li');
To be more specific, put a selector on your div
:
<div class="myUls">
<ul>....
</div>
$('.myUls ul:first-child').find('li');
Upvotes: 1
Reputation: 30453
Use eq
or nth-child
:
$div.find('ul:eq(0) li')
$div.find('ul:nth-child(1) li')
Notice that eq
is "0-indexed" and nth-child
is "1-indexed".
Also JQuery has shortcuts first-child
and last-child
.
Upvotes: 0