Reputation: 4342
I am trying to get all the href
tags of all links on a page, and put them in an array. I have the following code, but when I check the console I get the error Uncaught TypeError: Object has no method 'attr'
I'm not to sure where to go from here. Any ideas?
Code
function videoLinks() {
var videoLinks = $("a[id^=a_l_]").each(function() {
var linkArray = jQuery.makeArray(videoLinks);
console.log(linkArray.attr("href"));
});
}
Upvotes: 2
Views: 221
Reputation: 24488
This worked for me .. (from 'Matt Ball' code above)
$("a[id^=a_l_]").each(function() {
console.log(this.value);
});
Upvotes: 0
Reputation: 359786
$.makeArray
returns a native JavaScript array, not a jQuery object. Native JavaScript arrays do not have jQuery methods like .attr()
. Is this starting to make sense?
Passing videoLinks
to $.makeArray
simply does not make sense, since you're either passing the function videoLinks
, or the function-local videoLinks
which is already a jQuery object. So, I think this is more along the lines of what you're trying to do:
function videoLinks() {
$("a[id^=a_l_]").each(function() {
console.log(this.href);
});
}
That will log the href
attribute of every <a>
element with an id
that starts with 'a_l_'
. Perhaps instead you'd like to build up an array of those href
attributes instead of logging them. Then you'd use .map()
and .get()
:
function videoLinks() {
var hrefs = $("a[id^=a_l_]").map(function() {
return this.href;
}).get(); // ← note the .get() call
}
my ultimate goal is to return one of the links at random
Then you're almost there. Just get a random element from the hrefs
array:
function videoLinks() {
var hrefs = $("a[id^=a_l_]").map(function() {
return this.href;
}).get(); // ← note the .get() call
var randHref = hrefs[Math.floor(Math.random() * hrefs.length)];
console.log(randHref);
}
Upvotes: 4