Get li element onclick with pure javascript without applying onClick to each element

前端 未结 3 1572
醉梦人生
醉梦人生 2021-02-05 03:14

First of all I do not want to use jQuery, just pure javascript; please don\'t link to duplicate jQuery posts.

If I have a list like

相关标签:
3条回答
  • 2021-02-05 04:09

    You can use this:

    var link = document.getElementById("bulk");
    attachEvent(link, "click", EventHandler);
    
    function attachEvent(element, type, handler) {
        if (element.addEventListener) element.addEventListener(type, handler, false);
        else element.attachEvent("on"+type, handler);
    }
    
    function EventHandler(e) {
        console.log(e.target.id);
    }
    

    fiddle

    This work if li has children` elements:

    fiddle example with children

    0 讨论(0)
  • 2021-02-05 04:10

    You could add an event listener to the parent ul and then use e.target.id to get the id of the clicked element. Just check to make sure that the clicked element is actually an li since it's possible you may not be clicking on one.

    Example Here

    var ul = document.getElementById('bulk');  // Parent
    
    ul.addEventListener('click', function(e) {
        if (e.target.tagName === 'LI'){
          alert(e.target.id);  // Check if the element is a LI
        }
    });
    

    As pointed out in the comments, this approach won't work when the child of an li is clicked. To solve this, you would need to check to see if the parent element of the clicked element is the one that the click event is attached to.

    Example Here

    var ul = document.getElementById('bulk'); // Parent
    
    ul.addEventListener('click', function (e) {
        var target = e.target; // Clicked element
        while (target && target.parentNode !== ul) {
            target = target.parentNode; // If the clicked element isn't a direct child
            if(!target) { return; } // If element doesn't exist
        }
        if (target.tagName === 'LI'){
            alert(target.id); // Check if the element is a LI
        }
    });
    
    0 讨论(0)
  • 2021-02-05 04:11

    pass its id as parameter into the onclick-function.

    this.getAttribute('id')
    
    0 讨论(0)
提交回复
热议问题