0

I am using the tutorial from w3schools that lets you click on an item in a list and change the color of the background. I need to take the string from the list item and do something with it. So, I am starting with just writing to the console log.

    // Add a "checked" symbol when clicking on a list item
    var list = document.querySelector('ul');
    list.addEventListener('click', function(ev) {
        if (ev.target.tagName === 'LI') {
        ev.target.classList.toggle('checked');
        var result = document.getElementsBytagName('LI').innerHTML;
        console.log(result);
    }
 }, false);`

Thanks

2 Answers2

1

I'm not sure if this is what you're trying to do, but I think you can use the event.target object

var list = document.querySelector('ul');

list.addEventListener('click', function(event) {
    if (event.target.tagName === 'LI') {
        event.target.classList.toggle('checked');

        // get string of the clicked list item
        var result = event.target.innerHTML;

        // you could also use innerText to get string
        // content inside <li> without any html tags
        // var result = event.target.innerText;

        console.log(result);
    }
}

The event.target object returns whichever HTML DOM Element initiated the Event: https://developer.mozilla.org/en-US/docs/Web/API/Event/target

zk_
  • 71
  • 3
  • Thanks. It works but I get the string + x. Do you know how to get rid of the part. (I am trying to make a Microsoft add-in that will put signatures into an email. I need the text from the list to put into the signature.) – Ryan Adams Mar 31 '21 at 16:54
  • @RyanAdams can you share the HTML part of your code? It seems like span is a child element to your list items. Also, there's another stack overflow link about how to get just the first text node of an HTML element here: https://stackoverflow.com/questions/6520192/how-to-get-the-text-node-of-an-element – zk_ Mar 31 '21 at 16:56
  • Thanks. I figured it out. var result =event.target.firstChild.nodeValue; worked great. Thanks again. – Ryan Adams Mar 31 '21 at 17:42
0

Here is an example of console.log that might help you

index.html

<ul>
  <li class="myList">1</li>
  <li class="myList">2</li>
  <li class="myList">3</li>
</ul>

index.js

let elements = document.getElementsByClassName("myList");

for (element of elements) {
  element.addEventListener('click', function(event) {
    console.log(event.target.innerHTML);
  })
}
Yana Trifonova
  • 586
  • 7
  • 28