I am new to JS and am trying to write a simple bookmarklet for a website that has divs with class "collapseable" set to display: none; I want by one click to set all elements with class "collapseable" to display: block. Browsing this website, I managed to put together the following code, which works fine when I paste it in Google Chrome's JS console: it returns the value "block" but the effect on the website is the one I seek. However, when I create a bookmarklet with URL javascript:mycode... , it only brings up a blank page with the text "block".
Here is my code, I would very much appreciate if somebody could tell me what I'm doing wrong:
javascript:function getElementsByClassName(classname, node) {
if(!node) node = document.getElementsByTagName("body")[0];
var a = [];
var re = new RegExp('\\b' + classname + '\\b');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;};
var elems = getElementsByClassName('collapseable');
for (var i=0;i<elems.length;i+=1){
elems[i].style.display = 'block';}
When I tried making a bookmarklet myself, I had the same problem. My solution was to use void (function({ /* your code */ })()
.
javascript:void(function(){
var getElsByCN = document.getElementsByClassName ||
function(classname, node) {
if(!node) node = document.body;
var a = [],
re = new RegExp('\\b' + classname + '\\b'),
els = node.getElementsByTagName("*");
for (var i = 0, j = els.length; i < j; i++)
if (re.test(els[i].className))
a.push(els[i]);
return a;
};
var elems = getElsByCN('collapseable');
for (var i = 0; i < elems.length; i++)
elems[i].style.display = 'block';
)();
This works because it returns an undefined
value due to the use of void
. When your script wrote block
on the page, it was likely because that was the last value set/accessed by the funtion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.