Reputation: 44303
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
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.
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
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
Reputation: 985
There is 'visibility' and there is 'display'. They are quite different beasts.
W3Schools:
Upvotes: 0