Rich
Rich

Reputation: 21

How do I grab (and use) the element being clicked in javascript/jQuery?

So basically what I'm trying to do is apply one click event, and then using event.target determine exactly what was clicked on. After determining what was clicked on, I can then use that to manipulate the DOM. Below is the closest I could get to giving me something somewhat usable, but it doesn't give me 'exactly what I clicked on'.

$("body").click(function(event) {

    alert(event.target.nodeName); // Alerts the type of element you clicked on, but doesn't return anything 'usable' to manipulate the DOM

});

Upvotes: 2

Views: 520

Answers (1)

SooDesuNe
SooDesuNe

Reputation: 10030

for jQuery, $(event.target) will give you a jQuery object containing your clicked element. Then you can manipulate to your hearts content.

--UPDATE

I see that your binding the click() event to $('body') So when you click the body of your document, click is fired with e.target being the body. You probably want to attach that click event listener to a more specific element, see: http://jsfiddle.net/nn4sJ/8/ for an example

Upvotes: 6

Related Questions