with(something)

March 11, 2007

I discovered a nice little shortcut for setting element properties in JavaScript. Instead of saying:

nameDiv = document.createElement('div')
nameDiv.className = 'nameDiv';
nameDiv.innerText = showName;
nameDiv.title = showName;

You can kind of “zoom in to” the element:

with (nameDiv = document.createElement('div'))
{
  className = 'nameDiv';
  innerText = showName;
  title = showName;
}

Much nicer!