Reputation: 1853
I have a control which allows users to sort the <li>
in whatever order they want. when the form submits I want to grab the text inside the <li>
for each <li>
put into an array, in the order on the form.
<ul id="sortable">
<li class="ui-state-default">
<span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Protective Services
</li>
<li class="ui-state-default">
<span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Engineering Services and Public Works
</li>
</ul>
I am grabbing the <li>
's with:
var ar = [];
ar = document.getElementById("sortable").getElementsByTagName("li");
I then go through the array:
for(i = 0; i < ar.length; i++){
alert(ar[i].text()); //ar[i].anything results in console errors.
}
ar[i] displays [object HTMLLIElement]
for every <li>
available.
if I try to access the .text/.val/id properties inside the items i get a console error. So I'm assuming this has to do with a parsing/conversion issue?
How do I properly create an array that looks like protective services,Engineering Services and Public Works
and NOT like [object HTMLLIElement],[object HTMLLIElement]
? Or how do I access my text information from the <li>
as a [object HTMLLIElement]
?
Upvotes: 2
Views: 7153
Reputation: 310
jQuery solution:
$('li', '#sortable').each(function(){
alert($(this).text());
});
Or to fix your solution in pure JS:
var ar = [];
ar = document.getElementById("sortable").getElementsByTagName("li");
for (i = 0; i < ar.length; i++) {
alert(ar[i].innerText);
}
See fiddle.
Upvotes: 0
Reputation: 3412
Use :
var ar = [];
var listItems = $("#sortable li");
listItems.each(function(li) {
ar.push($(this).text());
});
Working here: http://jsfiddle.net/csdtesting/0uddfms6/
Upvotes: 0
Reputation: 42736
You need to use the properties ar[i].innerText
or ar[i].textContent
on DOM nodes. The method .text()
would be used if you had a jQuery object
var lis = document.getElementById("sortable").getElementsByTagName("li");
var data = [];
for(var i=0; i<lis.length; i++){
data.push(lis[i].innerText);
}
var jsonFormated = JSON.stringify(data);
document.getElementById("log").innerHTML = jsonFormated;
<ul id="sortable">
<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Protective Services</li>
<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Engineering Services and Public Works</li>
</ul>
<div id="log"></div>
Upvotes: 1
Reputation: 1384
the problem is that you work with the HTMLElement, which is of vanilla js, not jQuery. Try .innerHTML
instead of .text()
Upvotes: 0
Reputation: 484
For a pure javascript solution use the innertext property
alert(ar[i].innerText);
Fiddle: http://jsfiddle.net/3fjursaw/
Upvotes: 3
Reputation: 1547
You need to get the jQuery object in order to use text()
:
alert($(ar[i]).text());
Upvotes: 1