user656925
user656925

Reputation:

Can I reduce this Javascript code?

Can I reduce

function n()
  {
  var a; 
  if(a = document.getElementById('fb0')) 
    {
    a.onclick = i0;
    document.getElementById('fb1').onclick = i1;
    }
  }

to

function n()
  {
  if(document.getElementById('fb0').onclick = i0) 
    {
    document.getElementById('fb1').onclick = i1;
    }
  }

I don't have a debugger right now. I know that document.getElementById('fb0') returns a value because the first snippet works fine. But does it need the assignment to be evaluated in the if statement?

Upvotes: 1

Views: 202

Answers (5)

BrunoLM
BrunoLM

Reputation: 100371

No, you can't.

document.getElementById('fb0'), as the function name already says, returns the html element with has the id equal to fb0. After that you are accessing the attribute onclick. But it the get fails it will break the script.

On the first scenario you test if the assignment works, if does it means the element exists and will only execute if it exists.

Those are different behaviors.

Upvotes: 1

user113716
user113716

Reputation: 322562

If you do a lot of DOM selection by ID, make a shortened version of that method:

function byId( id ) { return document.getElementById(id); };

function n() {
  var a; 
  if(a = byId('fb0')) {
    a.onclick = i0;
    byId('fb1').onclick = i1;
  }
}

In this case, doing the assignment inside the condition doesn't save you any characters. It's the same length to do it with the declaration.

function byId( id ) { return document.getElementById(id); };

function n() {
  var a = byId('fb0'); 
  if(a) {
    a.onclick = i0;
    byId('fb1').onclick = i1;
  }
}

Upvotes: 0

Prusse
Prusse

Reputation: 4315

To check if "document.getElementById('fb0')" returns an element or null, the second version don't do it and an error will be throw if there is no element with id "fb0". The second version is ok if you don't remove the "fb0" element from the DOM at some point.

Upvotes: 1

carlosfigueira
carlosfigueira

Reputation: 87293

Not really; if getElementById('fb0') doesn't return anything your page will get an error, and in the first case it wouldn't.

Upvotes: 1

adarshr
adarshr

Reputation: 62603

That would fail if document.getElementById('fb0') were not to exist. document.getElementById('fb0').onclick wouldn't mean much in that case.

Upvotes: 0

Related Questions