0

I am trying to propagate events with jQuery using the code below:

$(document).ready(function() {
$('#main').click(function(e){
var el = e.target.nodeName;
var $jObj = $(el);//jQuery object
$jObj.css('color','green');
});
});

This is the simple html code:

<div id="main">
<p>Test one</p>
<p>Test two</p>
<p>Test three</p>
</div>

Now, If I click on one of the p elements not only the selected p changes the color to green, but all p. I cannot understand the resaon. According to the jQuery script above only the selected <p> should change the colour. What I am doing wrong?

0

4 Answers 4

2

According to the jQuery script above only the selected p

I doubt that. You are selecting all p elements:

var el = e.target.nodeName; // el = "P"
var $jObj = $(el);//jQuery object // equiv to $("p")

e.target.nodeName is the value "P" which you then use as selector, and $("P") selects all p elements.

To only select the event target, pass the DOM element itself to jQuery:

$(e.target)

Relevant documentation: jQuery(element), event.target.

$(document).ready(function() {
$('#main').click(function(e){
var $jObj = $(e.target);//jQuery object
$jObj.css('color','green');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<p>Test one</p>
<p>Test two</p>
<p>Test three</p>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Felix, thanks for your answer. Now the script is workink properly.
0

Try this out :

 $(document).ready(function() {
      $('#main > p').click(function(e){
         $(this).css('color','green');
      });
    });

Comments

0

$(document).ready(function() {
  $('#main').find('p').on('click', function(){
      $(this).css('color','green');    
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<p>Test one</p>
<p>Test two</p>
<p>Test three</p>
</div>

Comments

0

Try this way to event delegate using on of JQUERY, when you click on p element, assign this to a variable and then use it as selector object before apply css

$(document).ready(function() 
 {
   $('#main').on('click','p',function(e)
   {
    var el = this;
    var $jObj = $(el);//jQuery object, see here carefully
    $jObj.css('color','green');
   });
 });

See DEMO

Comments

Your Answer

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.