jquery getting html elements by type and class
I'm trying to get a list of link titles from a wikipedia page. I downloaded the HTML and now I'm trying to run some javascript/jquery code to get this going. Here's what开发者_如何学运维 I have so far...
var elements = $("ul > li");
alert(elements.length);
alert(elements.get(0).val());
The first alert gives me "505", which looks about right (there's quite a few of these elements).
My questions are how do I filter elements $("ul > li")
by class name as well? Say the particular elements I want have class "class1".
The second alert doesn't give me anything, though elements.get(0)
tells me object HTMLLIelement
which is good I guess. So I'm not able to access a particular property that I want (say, 'title').
Thanks for the help guys.
My questions are how do I filter elements $("ul > li") by class name as well? Say the particular elements I want have class "class1".
It's all CSS selector syntax.
$("ul > li.class1")
The second alert doesn't give me anything, though elements.get(0) tells me "object HTMLLIelement" which is good I guess.
This is because .get()
returns a plain DOM element, not a jQueryified one. Use .eq()
instead:
elements.eq(0).val();
// to get the title:
elements.eq(0).prop('title');
// or if you're using jQuery <1.6,
elements.eq(0).attr('title');
if the (ul > li) element has 3 "a" (link) elements that I want, how do I get the first one?
Use :first
or .first()
.
$("ul > li.className") should be all you need.
how do I filter elements $("ul > li") by class name as well?
$("ul > li.class1")
To get title attribute:
elements.eq(0).attr('title');
精彩评论