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.
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.
Share Improve this question edited Jun 6, 2011 at 17:26 Naftali 146k41 gold badges247 silver badges304 bronze badges asked Jun 6, 2011 at 17:24 JDSJDS 17k47 gold badges171 silver badges234 bronze badges 1- 2 Here you can find up-to-date jQuery documentation. – Pointy Commented Jun 6, 2011 at 17:27
3 Answers
Reset to default 4My 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');