3

I create my Html elements using java script createElement().But I cannot select any of the html elements in JQuery -- $("p").on("click",function(){}) . It works for $(document) though. My JQuery script is at the end of the body in the html page. But when inspect elements is checked in the browser after page creation html elements are below the scripts.

I have seen there many other similar questions but none of them worked. Please help me solve this I have been working on this for couple of days now and its taking me no where.

Fabrício Matté
70.3k27 gold badges135 silver badges168 bronze badges
asked Jun 11, 2013 at 6:35

2 Answers 2

11

For dynamically created elements use:

$(document).on('click', 'p', function(){
 console.log("clicked");
});

jsFiddle demo, showing assigning the click event before creating the element.

answered Jun 11, 2013 at 6:38
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot,it worked.I cant believe i spent this much of time for this. Thanks again.
0

use live instead of on.

$("p").live("click",function(){}

Edit:

use of live is deprecated we can use on but by working from thee document, and not from an element.

Use:

$(document).on( 'click', '.someClass', doSomething);

Instead of:

$('.someClassParent').on( 'click', '.someClass', doSomething);

answered Jun 11, 2013 at 6:39

5 Comments

I tried many time for dynamically generated contents, where on not work live works, :)
That's not really the point - live has already been removed from the jQuery core in the latter versions, and shouldn't be used since it was deprecated. A direct equivalent to live is the on variation with the descendant selector as MrCode answered. Ref: stackoverflow.com/questions/8021436/… jquery.com/upgrade-guide/1.9/#live-removed api.jquery.com/live
Sounds like you were using a very old version then, before .on was implemented.
O yes, i think it is the case i was using an older version. What i understood we can use $(document).on( instead $("p").on(, we can work from the document, and not from an element. forum.jquery.com/topic/…
Yes, that is correct. The latter won't work for elements that are not yet created in the DOM.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.