JQuery with HTML Order List and Unorder List

From CoderLearner
Jump to: navigation, search

unordered list

  • Use the id to define each list
<ul id="mylist">
	<li id="f1">Apple</li>
	<li id="f2">Banana</li>
	<li id="f3">Coconut</li>
	<li id="f4">Pear</li>
	<li id="f5">Mango</li>
</ul>

Get value of unordered list item

  • Use $.map() method to get all the list items inside ul and store them into the myIds array.
  • As the myIds is an array, its index starts from 0.
$(document).ready(function() {
	var myIds = $('#mylist li').map(function(i,n) {
		return $(n).attr('id');
	});
				
	alert(myIds[0]);
});

Output

  • id="f1" is the first li, and it is index 0.
f1

Get values of list

$(document).ready(function() {
	var myIds = $('#mylist li').map(function(i,n) {
		return $(n).attr('id');
	}).get().join(',');
				
	alert(myIds);
});

Output

f1,f2,f3,f4,f5

Example 1: Get text values of the list

$(document).ready(function() {
	var myIds = $('#mylist li').map(function(i,n) {
		return $(n).text();
	});
				
	alert(myIds[0]);
});

Output

Apple

Example 2: Get text values of the list

$(document).ready(function() {
	var myIds = $('#mylist li').map(function(i,n) {
		return $(n).text();
	}).get().join(',');
				
	alert(myIds);
});

Output

Apple,Banana,Coconut,Pear,Mango