Variables of DOM objects

I tried to set an onclick event with:

where node_b is a pointer to a DOM object: node_b = document.getElementById(“a”)

The reason I passed a DOM object into a variable, was to avoid searches document.getElementById() each time.

However, it will not work. I am confused.
I cannot figure out if it a a mistake of mine or just the way javascript works.

Could anyone explain why I cannot use variables as DOM objects in order to avoit each time a tree search document.getElementById(“a”)?

Bellow is given the code with explanation when it works and when it fails.

function by_id(id){
var el = document.getElementById(id);
alert(‘by id: id=’+id);
alert(‘by id: el=’+el);
} ;

function by_el(el){
alert(“” // here id is defined

function visibility_on_off_by_id(id){ // id is a string with
var el = document.getElementById(id);
var s =;
if (s == ‘block’) {
document.getElementById(id).style.display = ‘none’;
} else {
document.getElementById(id).style.display = ‘block’;
alert(‘out of vis on off by id’)

function visibility_on_off_by_el(el){ // el is a pointer to DOM object ; it won’t work!
alert(“” ; // id is not defined
var s =;
if (s == ‘block’) { = ‘none’;
} else { = ‘block’;

alert(‘out of visibility_on_off_el’);


<div id=“a”></div>
<div id=“b”></div>

var node_a=document.getElementById(‘a’)
var node_b =document.getElementById(‘b’)
var id_b =


// works fine up to this point
// however if I try to attach events won’t work. See bellow:

// I sent the variable node_b which is a pointer toward a DOM element (as I understand)
// The advantage wound had been that I don’t have to search in DOM tree with document.getElementById()
// It won’t work!

node_a.setAttribute(“onClick”,“visibility_on_off_by_id('”+id_b+“');”); // it will not work
// I sent the variable by it’s name but I have to search the corresponding DOM object in visibility_on_off_by_id
// It will work!

// why node_a.setAttribute(“onClick”,“visibility_on_off_by_el('”+node_b+“');”); wont work? )



You could do this instead:

node_a.onclick = function () {

That worked. Many thanks.