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é
  • 69,329
  • 26
  • 129
  • 166
user1236173
  • 53
  • 1
  • 4

2 Answers2

10

For dynamically created elements use:

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

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

MrCode
  • 63,975
  • 10
  • 90
  • 112
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);

Mansoor Jafar
  • 1,458
  • 3
  • 15
  • 31
  • I tried many time for dynamically generated contents, where on not work live works, :) – Mansoor Jafar Jun 11 '13 at 06:41
  • 2
    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: http://stackoverflow.com/questions/8021436/jquery-1-7-turning-live-into-on http://jquery.com/upgrade-guide/1.9/#live-removed http://api.jquery.com/live/ – Fabrício Matté Jun 11 '13 at 06:46
  • Sounds like you were using a very old version then, before `.on` was implemented. – MrCode Jun 11 '13 at 06:46
  • 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. http://forum.jquery.com/topic/live-is-deprecated-but-on-doesn-t-work-on-not-existent-markup – Mansoor Jafar Jun 11 '13 at 06:51
  • Yes, that is correct. The latter won't work for elements that are not yet created in the DOM. – MrCode Jun 11 '13 at 06:52