Subho Subho - 5 months ago 8
jQuery Question

how to get the value of dynamically created <p>

I am creating multiple

<p></p>
elements dynamically in jquery.

var output = '<p>' + results.length + ' matches found</p>';
$.each(results, function (index, result) {
output += '<p class="'+result.text+'">- ' + result.text + '</p>';
});
$('#search-output').html(output);


Now when i click on the
<p>
elements i want the text value. I tried like

$('#search-output').click(function(e){
var data= $(this).text();
console.log(data);
$("#output").text(data);
})


But then all the contents of #search-output is showing. I want to get the value of the
<p>
I clicked. any help

Answer

Read about Event delegation

$('#search-output').on('click', 'p', function(e){
    var data= $(this).text();
    console.log(data);
    $("#output").text(data);
});