MazeJoaco MazeJoaco - 2 years ago 94
HTML Question

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

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 generated.

function get_friends(items){

if(items != undefined){
if (items.length != 0){
var html_friends_list = "";

for(var count = 0; count < items.length; count++){
if(items[count].subscription == "both"){
var display_name = Strophe.getNodeFromJid(items[count].jid);

html_friends_list = html_friends_list + "<li style='font-size:19px' id='open_chat-" + items[count].jid + "'>" + "<a href='chat-js/index.html'>" + display_name + "<span class='block-list-label' id='" + items[count].jid + "_unread_messages" + "'>0</span><span class='block-list-label' id='" + items[count].jid + "_change_status" + "'></span></a></li>";


document.getElementById("friends-list").innerHTML = html_friends_list;

As a said I want to save the value of the text and the id of any li element clicked.


Answer Source

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');{
  listItem.addEventListener('click', function(e){

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download