0

HI
I have this js function for pulling out a couple of links which I want to add onclick handlers to... but IE can't find the rel attribute the way Im doing it, Im assuming it can another way, but I dont know how?!


this works in Chrome, but not IE... the category_links.length yields a fat 0.

function get_product_categories_links(){
	var links = document.getElementsByTagName('a');
	var category_links = [];
	for(var x in links){
		if(links[x].rel == 'link_category')
			{
				category_links.push(links[x]);
			}
	}
	return category_links;
}
2
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by Airshow
0

Lifeworks,

Try :

...
if(links[x].getAttribute('rel') == 'link_category')
...

Or do the whole thing in one line with jQuery :

function get_product_categories_links(){
    return $('a[rel=link_category]').toArray();
}

Airshow

0

Hi Airshow,
Thanks for the assist, unfortunstely still no joy.... the getAttribute('rel') doesn't even work in Chrome...

I get 'Uncaught TypeError: Object 40 has no method 'getAttribute''

Is there a problem with browsers treating links as something other than objects? I notice if I alert(links[x]), then it outputs the href...

0

LifeWorks,

Then the line for(var x in links){ needs looking at.

Try

for(var x=0; x<links.length; x++) {
  if(links[x].getAttribute('rel') == 'link_category') {
    category_links.push(links[x]);
  }
}

Airshow

Edited by Airshow: n/a

0

Victory!!!

What the flip, I went through all my code and changed every for(var i in array) to the for(var i = 0; i<array.length; i++) and it worked fine.

Thanks airshow!

1

Lifeworks,

Sorry I should have spotted that first time.

  • for(var prop in obj) is good for objects
  • for(var i=0, i<array.length; i++) is good for arrays.

Just to muddy the waters, javascript arrays can be "sparse" (non-sequential indexes) or "associative" (indexed with strings not integers). Such arrays can be addressed as if they were objects with for(var prop in obj) .

However, in the case of var links = document.getElementsByTagName('a'); , links is neither a straightforward object nor array. It is a "collection", often described as being "array-like". I don't know exactly why but for(var i=0, i<array.length; i++) works and for(var prop in obj) sort of works but there's an extra element of type Number, not one of the collection.

Airshow

Edited by Airshow: n/a

Votes + Comments
Useful advice, knowledgeable input, not just guess work
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.