-2

I am trying to make a bookmarklet that I can use to quickly toggle the class/id of elements. I found this [old] code for toggling highlighting links. I have read that the with statement should be avoided unless you are using use strict;. I couldn't find any walk through on how with would look like if, and not sure how it would look

javascript: for (nIx5Bs = 0; nIx5Bs < document.all.length; nIx5Bs++) {
  if (document.all[nIx5Bs].tagName == 'A') {
    with(document.all[nIx5Bs].style) {
      if (backgroundColor == 'yellow') {
        void(backgroundColor = document.bgColor)
      } else {
        void(backgroundColor = 'yellow')
      }
    }
  }
}

I found another bookmarklet to show ids, but it isn't togglable.

javascript: var t = document.getElementsByTagName('div');
for (i = 0; i < t.length; i++) {
  void(t[i].style.padding = '5px;');
  b = t[i].className;
  h = t[i].innerHTML;
  void(t[i].innerHTML = '<p style=\'color:red;font-weight:bold;\'>' + b + '</p>' + h);
}

Any hints to make this togglable would be great.

Ryan B
  • 3,364
  • 21
  • 35

1 Answers1

1

with is attempting to block scope your variable before block scoping was a thing :), it has nothing to do with your loop.

It is saying inside this code block start at document.all[nIx5Bs].style and any variable referenced (backgroundColor) is appended to that point. More modern code would use let and const to block scope

for (let i = 0, max = document.all.length; i < max; i++) {
  let doc = document.all[i];

  if (doc.tagName === 'a') { 
    let style = doc.style; 
    if (style.backgroundColor !== 'yellow') {
      style.backgroundColor = 'yellow';
      continue;
    }
    style.backgroundColor = document.bgColor;
  }
}
D Lowther
  • 1,609
  • 1
  • 9
  • 16