There is a textarea#text and a separate div . When you enter text ( oninput ), an ajax request is formed, which prints up to 600 pieces ( p.matches ) in a div (previously completely empty), in which characters from textarea are found. When I double click on any of p.matches, I need to output its innerHTML to the console. I can not link two code fragments into one ...

The first:

 window.onload = function(){ var text = document.querySelector('#text'); var old_classifieds = document.querySelector('#old_classifieds'); text.oninput = function(){ var find = 'find=' + text.value; var xhr3 = new XMLHttpRequest(); xhr3.open('POST', 'findPhone.php'); xhr3.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr3.send(find); xhr3.onreadystatechange = function(){ if(xhr3.readyState == 4 && xhr3.status == 200){ old_classifieds.innerHTML = xhr3.response; } else{ old_classifieds.innerHTML = 'Ошибка!'; } } } } 

Second:

 var matches = document.querySelectorAll('p.matches'); matches.forEach(function(item){ item.ondblclick = function(){ console.log(item.innerHTML); } }) 

I think the fact is that when the p.matches page loads, it does not exist yet and is formed by a php handler. But when they exist and enter code number 2 into the console, everything starts working.

    1 answer 1

    Option 1:

     ... if(xhr3.readyState == 4 && xhr3.status == 200){ old_classifieds.innerHTML = xhr3.response; var matches = document.querySelectorAll('p.matches'); matches.forEach(function(item){ item.ondblclick = function(){ console.log(item.innerHTML); } }); } ... 

    Option 2:

     var old_classifieds = document.querySelector('#old_classifieds'); old_classifieds.addEventListener("dblclick", function(e) { if (e.target.tagName == "P" && e.target.classList.contains("matches")) { console.log(e.target.innerHTML); } }); 
     <div id="old_classifieds"> <p class="matches">The walrus and the carpenter</p> <p class="matches">Walked for a mile or so...</p> </div>