1

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?

ofek tal
  • 21
  • 3
  • 1
    What did you find when you googled: *"How to get element content in javascript"*? – Reyno May 17 '22 at 13:28
  • @Reyno First you need to ask if he googled at all :) – EzioMercer May 17 '22 at 13:29
  • I didn't find the right solution. I saw it's possible to check if an element was clicked but not to get its content. – ofek tal May 17 '22 at 13:30
  • 1
    @EzioMercer of course I googled it.. I have been looking for the answer but I didn't find my solution so I hoped I could find help here... :) – ofek tal May 17 '22 at 13:31
  • @ofektal You need text content or with HTML tags? – EzioMercer May 17 '22 at 13:31
  • @EzioMercer I need text content. Like the example I put in the question, I want to get the text content (in that case - '10'). – ofek tal May 17 '22 at 13:33
  • Does this answer your question? [How to get the pure text without HTML element using JavaScript?](https://stackoverflow.com/questions/6743912/how-to-get-the-pure-text-without-html-element-using-javascript) – EzioMercer May 17 '22 at 13:34
  • No, because I need to know what element was clicked. And then, to take its text content. – ofek tal May 17 '22 at 13:37
  • I want to get the whole element and through it I'll get the text content. – ofek tal May 17 '22 at 13:38
  • This function doesn't include anything right now. – ofek tal May 17 '22 at 13:39
  • 1
    The receiving function gets an event object as parameter. You can access the clicked element with event.target and get the content with event.target.innerText. – Onki Hara May 17 '22 at 13:40
  • @Onki Hara I tried it now, it works!! Thank you and all the others who helped me :) really appreciate it! – ofek tal May 17 '22 at 13:44

1 Answers1

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>
James
  • 20,957
  • 5
  • 26
  • 41