views:

35

answers:

2

What I'm aiming for is for jQuery to look at the element I've just clicked on (for example a p or an li tag), then apply a styling to all instances of that element (so all p tags on the page).

This is my code so far, but it only applies the styling to the single element that has been clicked on.

$("article *", document.body).click(function (e) {
  e.stopPropagation();
selectedElement = $(this);
$(selectedElement).css("border", "1px dotted #333")
});

Would appreciate any help or advice!

+3  A: 
$('article *',document.body).click(
function(e){
    e.stopPropagation();
    var selectedElement = this.tagName;
    $(selectedElement).css('border','1px dotted #333');
}
);

Demo at JS Bin, albeit I've used the universal selector (since I only posted a couple of lists (one an ol the other a ul).

Above code edited in response to comments from @Peter Ajtai, and linked JS Bin demo up-dated to reflect the change:

Why run around the block once before you look at the tagName? How about var selectedElement = this.tagName;. Also it's e.stopPropagation(), since you're calling a method.

David Thomas
Perfect, thanks!
Chris Armstrong
You're quite welcome. =)
David Thomas
Why run around the block once before you look at the `tagName`? How about `var selectedElement = this.tagName;`. Also it's `e.stopPropagation()`, since you're calling a method.
Peter Ajtai
+2  A: 

I don't know how many elements are nested under your article elements, but it would seem wasteful to add click event handlers to all of them using *.

Instead, just add the handler to article, and get the tagName of the e.target that was clicked.

$("article", document.body).click(function ( e ) {
    e.stopPropagation();
    $( e.target.tagName ).css("border", "1px dotted #333")
});

This will be much more efficient.

patrick dw
+1 - for efficiency
Peter Ajtai