Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass an HTML element as an argument to a Javascript function?

i have a chat window which has a close button(input type='image') and onclick i want to remove the chat window from the parent node and i use this code

closeBtn.setAttribute("onclick", "return closeContainer(cc" + friendId + ");");

please note that this button is created through javascipt and the cc223423432 (say) will be the id of the chat window

here is my code to remove it

function closeContainer(ccId) {
    var x = ccId;
    x.parentNode.removeChild(x);
    //..........
}

now in IE8 and Chrome it finds the passed argument as HTMLDIV and works fine but in firefox it give an error cc223423432 is undefined any idea why???

i know i can always do a document.getElementByID and then remove it but please if there is anything i am missing please tell

like image 497
Pankaj Kumar Avatar asked Dec 07 '25 08:12

Pankaj Kumar


1 Answers

closeBtn.setAttribute("onclick", "return closeContainer(cc" + friendId + ");");

Don't use setAttribute to set event handlers... actually don't use setAttribute on an HTML document at all. There are bugs in IE6-7 affecting many attributes, including event handlers. Always use the ‘DOM Level 2 HTML’ direct attribute properties instead; they're reliable and make your code easier to read.

Lose the attempt to create a function from a string (this is almost always the wrong thing), and just write:

closeBtn.onclick= function() {
    return closeContainer(document.getElementById('cc'+friendId));
};

or even just put the closeContainer functionality inline:

closeBtn.onclick= function() {
    var el= document.getElementById('cc'+friendId);
    el.parentNode.removeChild(el);
    return false;
};

in firefox it give an error cc223423432 is undefined any idea why???

Because IE makes every element with an id (or in some cases name) a global variable (a property of window). So in IE you can get away with just saying cc223423432 and getting a reference to your object.

This is a really bad thing to rely on, though. As well as not existing in other browsers, it clutters up the global namespace with crap and will go wrong as soon as you do actually have a variable with the same name as an id on your page.

Use getElementById to get a reference to an id'd node instead, as above. This works everywhere and is unambiguous.

like image 173
bobince Avatar answered Dec 09 '25 22:12

bobince



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!