1

I want the index of the search results when they are being clicked and I have used the following code:-

$('#results').append('<div class="res"><p class="clickable"><a id="select">'+dis[searchResult[i]]+'</a></p></div>');
var g = document.getElementById("select");
for (var j = 0; j<g.dis.length; j++)
{
    g.addEventListener('click',function(index){
    console.log(index);
    });
     }

But that gives the following error:-

search83.js:27 Uncaught TypeError: Cannot read property 'length' of undefined
    at HTMLInputElement.<anonymous> (search83.js:27)
    at HTMLInputElement.dispatch (jquery.min.js:2)
    at HTMLInputElement.v.handle (jquery.min.js:2)
  • You need to post a [mcve] - why not use jQuery for the click handler? – mplungjan Sep 20 '19 at 06:11
  • What is `g.dis` according to you? - Also it looks like you are looping to append too? If you are, then you are haivng duplicate IDs – mplungjan Sep 20 '19 at 06:13
  • Be aware that you can only have one item with an id. try using a class instead if you are appending multiple items. – Agoose Banwatti Sep 20 '19 at 06:14
  • `$("#results").on("click","clickable a",function() { console.log($(this.closest(".res")).index()) })` – mplungjan Sep 20 '19 at 06:15
  • It might be a duplicate, however you should understand what some of the issues are. The error says it all: 'length' of `g.dis` is `undefined`. `dis` is not a valid property of `g`, which is an HTMLElement. Also, notice how `getElementById` is singular. Just like @mplungjan mentioned, ids have to be unique and `getElementById` is expected to return a single object at most. – Artur Sep 20 '19 at 06:22

0 Answers0