matt
matt

Reputation: 44303

javascript getElementsByClassName() always returns none?

I want to create the simplest bookmarklet for my browser.

javascript:document.getElementsByClassName('source').style.visibility='visible';

I have multiple div.source in my body. By default they are set to .source { display:none; } with css.

My console tells me: Uncaught TypeError: Cannot set property 'display' of undefined

When I click the bookmarklet all .source divs should be visible. What am I doing wrong here?

Upvotes: 8

Views: 32021

Answers (4)

lior bakalo
lior bakalo

Reputation: 450

Never itarate live HTML collection. it is extremly inefficient as every time you access a member of a live collection (including the length), the browser traverses the entire document to find the specific element. see here.

Here is the efficeint solution:

let divs = [...document.getElementsByClassName('source')];
divs.forEach(divEl => {
  divEl.style.display='block'
}

using [...HTMLcollection] perfix converts the HTMLcollection to an array, then you can itarate it.

Upvotes: 0

Dinesh
Dinesh

Reputation: 9

Go for display. It's works fine with many browsers and in many cases.

Upvotes: 0

erickb
erickb

Reputation: 6309

You might need to loop through the results, like this:

var divs = document.getElementsByClassName('source');
for(var i=0; i<divs.length; i++) { 
  divs[i].style.display='block'
}

And also as @ionoy mentioned, use display attribute. I hope that helps.

http://jsfiddle.net/erick/rb7bn/1/

Upvotes: 21

ionoy
ionoy

Reputation: 985

There is 'visibility' and there is 'display'. They are quite different beasts.

W3Schools:

visibility

display

Upvotes: 0

Related Questions