0

So I already have the code:

function addOpt(opti, id) {
  document.getElementById("options").appendChild(document.createTextNode(opti))
  // ID WILL BE USED LATER
}

but I now want to make it so that when you click on the text (opti) it runs a function.

Archie
  • 96
  • 7
  • https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener –  Dec 24 '20 at 16:14
  • 2
    add the click event listener: `element.addEventListener('click', addOpt);` – Yousaf Dec 24 '20 at 16:14
  • You can't bind events to text node afaik, you need to wrap it in a span or something – Alon Eitan Dec 24 '20 at 16:16
  • @Yousaf That would work but how would I add an ID to the text node? you need an id for addeventlistener afaik – Archie Dec 24 '20 at 16:17
  • @AlonEitan I've done it before with (I cant remember which) either onmousedown = "function()" or onclick = "function()" – Archie Dec 24 '20 at 16:17
  • Also use `data-id` attribute and save the `id` there, then read the attribute from within the event callback function – Alon Eitan Dec 24 '20 at 16:19
  • @AlonEitan Could you please give a code example? I'm not sure I understand – Archie Dec 24 '20 at 16:20

1 Answers1

-1

I don't think it's possible to add event listeners to text nodes. source: https://stackoverflow.com/questions/4789342/textnode-addeventlistener#:~:text=Text%20nodes%20are%20just%20plain,can't%20have%20event%20listeners. Correct me if I'm wrong.

function addOpt(opti, id) {
 var a=document.createElement('span');
 a.style.color='blue';
 a.addEventListener('click', (e)=> console.log('clicked'));
 var b= document.createTextNode(opti);
 a.appendChild(b);
  document.getElementById("options").appendChild(a)
  // ID WILL BE USED LATER
}
addOpt('child (click)','id');
<div id ='options'>
parent
</div>
sample
  • 392
  • 2
  • 10