Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  5] [ 3]  / answers: 1 / hits: 22915  / 15 Years ago, mon, october 5, 2009, 12:00:00

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


More From » firefox

 Answers
147

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.


[#98572] Tuesday, September 29, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
samarab

Total Points: 620
Total Questions: 95
Total Answers: 89

Location: Bonaire
Member since Wed, May 11, 2022
2 Years ago
;