How to loop loop through a UL LI
list to get my <a>
text values?
Here's what I have tried:
<ul class="tabs">
<li><a href='#tab1'>tabOne</a></li>
<li><a href='#tab2'>tabTwo</a></li>
<li><a href='#tab3'>tabThree</a></li>
<li><a href='#tab4'>tabFour</a></li>
</ul>
function test() {
var x = $("ul.tabs li").length
alert(x)
for (i = 0; i < x i++) {
}
}
You can use .each()
for this task:
//for each "ul.tabs a" elements $("ul.tabs a").each(function() { // $(this) represents to current iterated DOM element // $(this) is "a" element selector // If we were using a for(var i = 0;. . .) loop for arrayName[], $(this) would be arrayName[i] console.log($(this).text()); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="tabs"> <li><a href='#tab1'>tabOne</a></li> <li><a href='#tab2'>tabTwo</a></li> <li><a href='#tab3'>tabThree</a></li> <li><a href='#tab4'>tabFour</a></li> </ul>
for
loops are a good go to method, but be careful mixing jQuery methods and properties with plain JavaScript methods and properties. They do not recognize the other's objects.
Details commented in demo
// This jQuery Object is like an array-like object var lnx = $('.tabs a'); /* The .length property applies to any jQuery Object || Using let to define the increment variable is safe */ for (let i = 0; i < lnx.length; i++) { /* Since lnx is array-like, we can use bracket || notation to keep track of its current index || on each iteration. || The plain JavaScript property .textContent || works on lnx because the brackets and || index number dereferrences the jQuery Object || into a plain JavaScript Object */ var txt = lnx[i].textContent; // Log results on each iteration console.log(txt + '\\n'); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="tabs"> <li><a href='#tab1'>tabOne</a></li> <li><a href='#tab2'>tabTwo</a></li> <li><a href='#tab3'>tabThree</a></li> <li><a href='#tab4'>tabFour</a></li> </ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.