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;
}

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

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...

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

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!

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

commented: Useful advice, knowledgeable input, not just guess work +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.