Get text and id from an li element on click with pure JS

前端 未结 2 1967
逝去的感伤
逝去的感伤 2021-01-28 22:12

I\'ve been stuck with this for several days and I can\'t solve it.

I\'ve done it with jQuery with no problem, but I need it in pure JS.

This is how my list is ge

相关标签:
2条回答
  • 2021-01-28 23:01

    you haven't specified whether this is for a specific list or just any li on your page. The below will log the id and innerHTML components of any li on the page. Perhaps you may need to update the querySelector for your particular use case.

    var list = document.querySelectorAll('li');
    
    Array.prototype.slice.call(list).forEach(function(listItem){
      listItem.addEventListener('click', function(e){
        console.log(this.id);
        console.log(this.innerHTML);
      });
    });
    

    Here's a JSFiddle which I think demonstrates what you are trying to achieve.

    0 讨论(0)
  • 2021-01-28 23:06

    Jsfiddle

    Combination of james' answer and working example.

    function get_friends(items) {
        if (items != undefined) {
            if (items.length != 0) {
                var html_friends_list = "<ul>";
    
                for (var count = 0; count < items.length; count++) {
    
                    if (items[count].subscription == "both") {
    
                        html_friends_list = html_friends_list + "<li id='open_chat-" + items[count].jid + "'>"+ items[count].display_name +"</li>";
    
                    }
    
                }
                            html_friends_list = html_friends_list + '</ul>'
                document.getElementById("friends-list").innerHTML = html_friends_list;
            }
        }
    }
    

    Note: you should trigger prototype after your dom element created.

    0 讨论(0)
提交回复
热议问题