I get the error undefined is not a function
when running this code:
var links=$("li").find("a");//this works...has a length of 23
//then I run this
for(var i=0;i<links.length;i++){
links[i].attr("href");//this does not work
}
What can I do to obtain to get the href property from the link?
The elements of a jQuery object are DOM elements, not other jQuery objects, so they don't have jQuery methods. You can use the eq
method to access jQuery-wrapped versions of those elements:
for(var i=0;i<links.length;i++){
href = links.eq(i).attr("href");
}
Or just access the property directly:
for(var i=0;i<links.length;i++){
href = links[i].href;
}
In your example code you're not actually doing anything with the value though so you may want to sort that out too.
You should simply try :
$("li a").each(function(){
console.log($(this).attr('href'));
});
Or fix your code to create a jquery object to be able to use attr function :
for(var i=0;i<links.length;i++){
$(links[i]).attr("href");
}
Or simply use href :
links[i].href;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.