8

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?

peterh
  • 11,875
  • 18
  • 85
  • 108
matt
  • 42,713
  • 103
  • 264
  • 397

4 Answers4

21

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/

erickb
  • 6,193
  • 4
  • 24
  • 19
  • 2
    javascript:(function() { var divs = document.getElementsByClassName('source');for(var i=0; i – ionoy Mar 03 '11 at 11:19
  • `forEach` is a little cleaner, perhaps. `document.getElementsByClassName('source').forEach(function (elem) {elem.style.display = 'block'})` (or `none` when it comes to all those danged annoying animated holiday snowflakes blogs are sporting right now) – ruffin Dec 29 '14 at 19:29
0

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

Holger Brandt
  • 4,324
  • 1
  • 20
  • 35
Dinesh
  • 9
  • 1
  • Turning 'visibility' off behaves the same as setting opacity to zero: the contents become invisible while the layout doesn't change; or to say the same thing a different way there's now a blank space. This is hardly ever what you want. On the other hand turning 'display' off causes a reflow/relayout as though the element no longer existed at all. The space where it was will be closed up. This is almost always what you want. Both are standard parts of CSS - browser support isn't an issue. Use the one that will produce the desired behavior/appearance of your application. – Chuck Kollars Jun 11 '14 at 20:44
0

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

W3Schools:

visibility

display

ionoy
  • 975
  • 6
  • 19
  • that doesn't change anything. my console tells me: `Uncaught TypeError: Cannot set property 'display' of undefined` – matt Mar 03 '11 at 11:04
0

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.

lior bakalo
  • 440
  • 2
  • 9