homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

getting #ID of a clickable via jQuery

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

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)

<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)

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)

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)

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.

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved