Issue
I need some help with JavaScript. I want to add a click function to every node elements in my program and also want to add class name with the help of JavaScript. I mean by click function is that if I click on item it will close and if I again click on item fruits with appear. The following is my JavaScript code, and I am attaching live fiddle to so the program I am working with. Please I want the code with JavaScript not jQuery.
item
fruits
Orange
Banana
Mango
function generate(node) {
if (node.nodeType != 1) return "";
var html = "<li>" + node.nodeName + " = " + node.childNodes.length;
var htmlForChildNodes = "";
for (var i = 0; i < node.childNodes.length; i++) {
htmlForChildNodes += generate(node.childNodes[i]);
}
if (htmlForChildNodes) {
html += "<ul>" + htmlForChildNodes + "</ul>";
}
html += "</li>";
return html;
}
Solution
You may use the following in case if you wrap your list names with <a>
elements:
// ...
var html = "<li><a href='javascript:;'>" + node.nodeName + "</a>";
// ...
var a = document.getElementsByTagName('a');
for (var i = 0, len = a.length; i < len; i++) {
a[i].addEventListener('click', function() {
var ul = this.parentNode.getElementsByTagName('ul');
if (ul.length) {
ul[0].className =
ul[0].className.indexOf('collapsed') > -1
? ul[0].className.replace('collapsed', '')
: ul[0].className + ' collapsed';
}
return false;
}, false);
}
DEMO http://jsfiddle.net/32eVr/26/
Answered By - VisioN
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.