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"'
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.
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.
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.
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".
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('", "') + '"';
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