html - Javascript: Selecting List from UL -
var ul = document.getelementbyid("parent-list"); document.queryselectorall("#parent-list li").onclick = function() { alert('click!'); }
<ul id="parent-list"> <li id="item-1">item 1</li> <li id="item-2">item 2</li> <li id="item-3">item 3</li> <li id="item-4">item 4</li> <li id="item-5">item 5</li> <li id="item-6">item 6</li> <li id="item-7">item 7</li> <li id="item-8">item 8</li> <li id="item-9">item 9</li> </ul>
i'm trying have alert popup of item clicked when click on "li" element javascript only. know how in jquery can't figure out how javascript.
fiddle: https://jsfiddle.net/7jcksznz/1/
queryselectorall
returns html collection. need attach event each one. need loop on collection.
var lis = document.queryselectorall("#test li"); (var = 0; < lis.length; i++) { lis[i].addeventlistener("click", function() { console.log(this.innerhtml); }); }
<ul id="test"> <li>1</li> <li>2</li> <li>3</li> </ul>
a better option add 1 click on ul , use event determine li clicked.
document.getelementbyid("test").addeventlistener("click", function(event) { var li = event.target; console.log(li.innerhtml); });
<ul id="test"> <li>1</li> <li>2</li> <li>3</li> </ul>
Comments
Post a Comment