Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an array of list element contents in jQuery

I have a structure like this:

<ul>   <li>text1</li>   <li>text2</li>   <li>text3</li> </ul> 

How do I use javascript or jQuery to get the text as an array?

['text1', 'text2', 'text3'] 

My plan after this is to assemble it into a string, probably using .join(', '), and get it in a format like this:

'"text1", "text2", "text3"' 
like image 535
Christian Oudard Avatar asked Oct 29 '08 14:10

Christian Oudard


People also ask

How do you check if an array contains a value in jQuery?

The jQuery inArray() method is used to find a specific value in the given array. If the value found, the method returns the index value, i.e., the position of the item. Otherwise, if the value is not present or not found, the inArray() method returns -1.

How do you iterate through an array in jQuery?

The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

What is grep in jQuery?

The grep() method in jQuery finds the array elements that satisfy the given filter function. It does not affect the original array. This method returns the filtered array, i.e., the elements that satisfy the given filter function.

What is inArray in JavaScript?

Arrays are Objects Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements".


1 Answers

var optionTexts = []; $("ul li").each(function() { optionTexts.push($(this).text()) }); 

...should do the trick. To get the final output you're looking for, join() plus some concatenation will do nicely:

var quotedCSV = '"' + optionTexts.join('", "') + '"'; 
like image 98
Shog9 Avatar answered Oct 06 '22 01:10

Shog9