javajoemorgan Posted February 7, 2008 Share Posted February 7, 2008 I am writing a JS to change the class of a parent node of an A when clicked. Suppose I have: <ul> <li> <a href="java script:setClass(this.parentNode);">Click Me</a> </li><ul> And my JavaScript is: function setClass(node) { if (node.className != null) { if (node.className.indexOf(" myClass") != -1) node.className.replace(" myClass", ""); else node.className += " myClass"; } else node.className = " myClass";} It wasn't working. So, through a series of alerts, I learned that the incoming node is undefined.What am I missing? Link to comment Share on other sites More sharing options...
jesh Posted February 7, 2008 Share Posted February 7, 2008 You might try this instead: <a href="#" onclick="setClass(this.parentNode);return false;">Click Me</a> I ran your code and it looks like "this" in the "java script:setClass(this.parentNode)" references the window object rather than the anchor element. And, since there are no parent nodes for the window object, you're getting a null reference.I don't ever use "java script:function()" in the hrefs, so I don't really know why this is the case. Perhaps the execution path for the "java script:" is at the window rather than at the element. Stick to the DOM and use onclick and this should work for you. Link to comment Share on other sites More sharing options...
javajoemorgan Posted February 7, 2008 Author Share Posted February 7, 2008 You might try this instead:<a href="#" onclick="setClass(this.parentNode);return false;">Click Me</a> I ran your code and it looks like "this" in the "java script:setClass(this.parentNode)" references the window object rather than the anchor element. And, since there are no parent nodes for the window object, you're getting a null reference. Hmm... isn't that interesting! I hadn't thought it would reference all the way out. However, your suggestion solves the problem... good enough for me! Thanks. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.