Selector won't work with new inserted tag

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
cohq82
Forum Commoner
Posts: 43
Joined: Mon Apr 21, 2008 8:38 pm

Selector won't work with new inserted tag

Post by cohq82 »

Is anyone aware of this problem? For example, the code below simply just inserts new P tag below the existing P's. When I move mouse over each of the P, I should see color change. Or when I click on new P, I should be able to trigger the P click event. That did not happen. Anyone knows how to fix this? This is just an example since I tried to do something similar. Thanks

Code: Select all

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("p").click(function() {
        $("p").after("<p>Hello</p>");
    });
    
    $("p").hover(function() {
        $(this).css('color','red');
    },
    function() {
        $(this).css('color','black');
    });
  });
  </script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p>I would like to say: </p>
</body>
</html>
 
Last edited by Benjamin on Thu May 14, 2009 1:16 am, edited 1 time in total.
Reason: Changed code type from text to html.
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Selector won't work with new inserted tag

Post by kaszu »

You must use .live function to bind to P which aren't in the DOM yet.
cohq82
Forum Commoner
Posts: 43
Joined: Mon Apr 21, 2008 8:38 pm

Re: Selector won't work with new inserted tag

Post by cohq82 »

Thanks
Post Reply