'Getting the whole content of a clicked <li> element

This is my HTML line:

<li onclick="return open_create_event_screen();">10</li>

I want to get the content of this < li > element (which is '10') through the JavaScript function (open_create_event_screen()) that opens once the < li > element is clicked. Is it possible to do so?



Solution 1:[1]

Old way, where we put inline events into our HTML. The key is to pass this into the function, which is a reference to the element that was acted upon, you could also pass event, and determine the clicked element from the target property (two different approaches).

const open_create_event_screen = (obj) => {
  console.log("opening create event screen");
  console.log(obj.innerText);
}
<li onclick="open_create_event_screen(this);">10</li>

Here's a more modern approach, where our html is cleaner, and we do the work of assigning the event handlers in javascript.

const open_create_event_screen = (obj) => {
  console.log("opening create event screen");
  console.log(obj.innerText);
}

const lis = document.querySelectorAll(".eventThing>li");
lis.forEach(li => 
  li.addEventListener("click", () => open_create_event_screen(li))
);
<ul class="eventThing">
  <li>10</li>
  <li>20</li>
</ul>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James