Variables of DOM objects

I tried to set an onclick event with:
node_a.setAttribute(“onClick”,“visibility_on_off_by_el('”+node_b+“');”);

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.

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

function by_el(el){
alert(“el=”+el)
alert(“el.id=”+el.id) // here id is defined
}

function visibility_on_off_by_id(id){ // id is a string with
var el = document.getElementById(id);
alert(‘id=’+id);
alert(‘el=’+el);
var s = el.style.display;
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(“el=”+el)
alert(“el.id=”+el.id) ; // id is not defined
var s = el.style.display;
if (s == ‘block’) {
el.style.display = ‘none’;
} else {
el.style.display = ‘block’;
}

alert(‘out of visibility_on_off_el’);
}

</script>

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

<script>
var node_a=document.getElementById(‘a’)
var node_b =document.getElementById(‘b’)
var id_b = node_b.id

by_id(id_b);
by_el(node_b);

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

node_a.setAttribute(“onClick”,“visibility_on_off_by_el('”+node_b+“');”);
// 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? )

</script>

</body>
</html>

You could do this instead:


node_a.onclick = function () {
	visibility_on_off_by_el(node_b);
};

That worked. Many thanks.