How can I access <li> tags one by one in Javascript?
I have various <li>
elements in a label in my aspx page. I want to use Javascript to fetch one <li>
element at a time and perform so开发者_如何学Gome action on it. I have no idea how to do it;
which function should I use?
Earlier I got a list for the same in C#, but I can't iterate over it in Javascript, so I converted it to <li>
so that it can be accessed by Javascript.
var li = document.getElementsByTagName('li')
for (var i = 0; i < li.length; i++) {
//manipulate them how?
console.log(li[i]);
}
how are you trying to manipulate them? what would you do, this will insert them into an array called li and the for loop will cycle through. but what is it you want to do?
live example: http://jsfiddle.net/yTXuK/
Use document.getElementsByTagName("li")
This would return a collection of li's
If you're using jquery you can use a basic selector to get a jquery object containing the lis of <li>
s and then you can act upon them with each.
$('li').each(function(){
var li = $(this);
//code to manipulate li
});
document.getElementsByTagName('li')
will return an array of li elements.
Edit: You could optionally add an array of the data points to the page by printing out a script tag on the page instead of the li's. That way you don't have extra unneeded elements on the page.
try this:
var lis = document.getElementsByTagName("li");
精彩评论