0

I'm fetching items from an API and creating a list in the web-client. I need to add onclick in the span-element where the text strings should reside in order to call a script when the user clicks on it. I can't seem to insert the onlick attribute into the span-element.

HTML:

   <ul id="list">
        </ul>

Javascript:

array= array of strings fetched from api.

for(var i=0;i<array.length;i++) { 
    var string=array[i].text;
    var list= document.createElement("li");
    var span=document.createElement("SPAN");
    span.onclick="call()"; 
    var txt_node=document.createTextNode(string);
    span.appendChild(txt_node)
    list.appendChild(span);
    document.getElementById("list").appendChild(list);
}

is there an alternative way of making the span object clickable?

carasa
  • 1
  • 2
  • You can use `span.onclick=call;` – imvain2 Oct 13 '20 at 16:20
  • `` elements are not designed to be interactive, they won't get the focus and (for example) screen readers won't announce them as interactive. Use a ` – Quentin Oct 13 '20 at 16:24
  • `span.addEventListener('click', call)`, or `document.querySelector('#list').addEventListener('click', call)` (and then use the `event.target` property of the Event Object inside the `call()` function); but do remember Quentin's advice regarding usability. – David Thomas Oct 13 '20 at 16:24

0 Answers0