I have the following code.
HTML
<ul>
<li class="link"> link 1 </li>
<li class="link"> link 2 </li>
<li class="link"> link 3 </li>
<li class="link"> link 4 </li>
</ul>\
javaScript
YUI().use("node", function(Y){
Y.all(".link").on("click", function(em){
alert("you clicked on "+ index +"link .");
node = em.currentTarget;
node.addClass("clicked");
// alert(node.get("class"));
});
alert(Y.all("li").get("class"));
});
I have two queries on this.
1) While first alert it should show class name “link” but it give alert of some YUI_23123_ random number. Why so?
2) And I want to alert the index also. example when user click on third link it should alert “you clicked on 3 link” and I also want to use this index value in other event as well.
How we can achieve the index?
Interesting question!
For (1) Y.all(…) returns a NodeList. Unfortunately the return value of “get” for a nodeList is oddly another NodeList, which gets interpreted in the printing of the alert to what you see. Using “getAttribute” instead of “get” results in a more reasonable (though maybe not useful) output.
For (2) To achieve what you want, you will need to either explicitly loop over the NodeList or use “delegate”. Using “delegate” is far more efficient for the page and allows you to insert “li” items dynamically, but the “indexOf” might get noticeably slow with hundreds or thousands of list items.
Using each:
Using delegate: