Reputation: 4342
I am trying to search a page for links that contain the word playgame. If they found then I add them to an array. After that Select a random value from the array and use window.location
. My problem is that it says my indexof
is undefined. I not sure exactly that what means as I am still learning to use this feature of javascript.
example of link
<a href="playgame.aspx?gid=22693&tag=ddab47a0b9ba5cb4"><img src="http://games.mochiads.com/c/g/running-lion-2/_thumb_100x100.jpg"></a>
javascript
var gameLinks = document.getElementsByTagName("a");
if (gameLinks.href.indexOf("playgame") != -1) {
var links = [];
links.push(gameLinks.href);
var randomHref = links[Math.floor(Math.random() * links.length)];
window.location = randomHref;
}
Upvotes: 1
Views: 270
Reputation: 1074108
My problem is that it says my indexof is undefined
Not indexOf
, the thing you're calling it on. gameLinks
is a NodeList
, it doesn't have an href
property. You need to loop through the contents of the list to look at the individual element's href
property. E.g.:
var index, href, links, randomHref, gameLinks;
gameLinks = document.getElementsByTagName("a");
// Loop through the links
links = [];
for (index = 0; index < gameLinks.length; ++index) {
// Get this specific link's href
href = gameLinks[index].href;
if (href.indexOf("playgame") != -1) {
links.push(href);
}
}
randomHref = links[Math.floor(Math.random() * links.length)];
window.location = randomHref;
More to explore:
Upvotes: 2