Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

getting #ID of a clickable via jQuery



6:34 pm on Mar 21, 2013 (gmt 0)

10+ Year Member

How do I grab the CSS #ID of the clicked element below, so that I can execute subsequent commands on it:

<div id="ID1" onclick="clickable">Div 1</div>
<div id="ID2" onclick="clickable">Div 2</div>
<div id="ID3" onclick="clickable">Div 3</div>

Using script:

function clickable() {
// need to grab '#ID1','#ID2', or '#ID3' depending on which is clicked

I tried simply using $(this)... but it doesn't work.


12:47 am on Mar 22, 2013 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

<div id="ID1" onclick="clickable(this)">Div 1</div>

function clickable(el) {
alert(el.id); // gives ID1

Note that when onclick is set his way (as opposed to within javascript) the value must be a statement

onclick="clickable" BAD
onclick="clickable()" OK
onclick="clickable(this)" OK
onclick="alert(this.id)" OK


1:19 pm on Mar 22, 2013 (gmt 0)

10+ Year Member

Great, thanks. Glad I asked -- never would have gotten that on my own.

Just to follow up, the only way I could get el.id to work in a jQuery command was to use:

$("#" + el.id).show();

Is that the only/best way to code it? Seems a little complex for a simple var.


11:42 pm on Mar 22, 2013 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

For that you do not need to get the id or even give it an id in the first place.



5:06 pm on Mar 23, 2013 (gmt 0)

10+ Year Member

Ouch -- that was easy.

My javascript ignorance is showing. Some day I'll be able to afford a professional programmer to do my website. Until then, you guys are life savers.

Many thanks, DaveVk.

Featured Threads

Hot Threads This Week

Hot Threads This Month