How to select elements created with jQuery?

How can I select an element in jQuery made with jQuery?

For example, if I make a paragraph with jQuery and then select it further on, the selection doesn’t seem to work.

$('<p class="para">').appendTo('.el');

And then select it later in the program

     console.log('hi')
}```


In this case, this thing will not be consoled because the selection doesn't work.

Try it like this:

$('.el').on('click','.para', function () {
console.log('hi')
})
1 Like

This is working but will I be able to use the ‘this’ keyword with the paragraph?

Try it and see :slight_smile:
(the answer is yes).

.test{background:blue}

JS:


$('.el').on('click','.para', function () {
console.log('hi');
$(this).addClass('test');
})
3 Likes

In case of doubt you can always use event.target, which is just the element that triggered the event. That’s a bit more bullet proof anyway as the event object is getting explicitly passed to the handler function, whereas the this-binding is implicit and subject o changes during runtime (e.g. when using arrow functions, .bind(), .call() etc.).

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.