View Full Version : Return elements id

07-24-2011, 09:47 PM
Im working on a function where i need to return the active elements ID.
the element will have class="main" id="1" onmouseover="showSub()">

Would someone be able to write me a simple function which simply puts the elements ID number in an alert box? I can figure out the rest i need from that :).

Thanks, Tom

07-24-2011, 11:38 PM
Just for the records: An ID must not start with a number, it must begin with a letter A–Z or a–z.

07-24-2011, 11:39 PM
Ahh okay thanks :). In the end i gave up on ID and i did showSub(1) then function showSub(theID) { etc.

low tech
07-25-2011, 02:09 AM

a simple function which simply puts the elements ID number in an alert box?

<script type="text/javascript">
function showSub(id){
alert("The id is " + id);
<input type="text" name="test1" class="main" id="A122334" onmouseover="showSub(this.id)" />

07-26-2011, 06:54 AM

If you are comfortable with JQuery, you can use the below piece of code and get the ID of any element you like.

<!-- latest jquery include -->
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript" ></script>

<!-- function to return the element Id -->
<script type="text/javascript">
$('.hello').live('click', function() {
alert('ID of the clicked element - '+ $(this).attr('id'));

<!-- In html body add the code -->
<div id="div1-clicked" class="hello">Div Click</div>
<label id="label1-clicked" class="hello">Label Click</label>

The above example for 'click' event, for mouseover change 'click' to 'mouseover' in the script.

Hope that this will solve your problem.
I also attached the html file for your reference.

07-26-2011, 11:39 AM
I must say, it’s really stupid to install a 31KB library to perform such a basic task.

07-26-2011, 01:36 PM
I'll use libraries in my works and I feel comfortable with those libraries rather than using plain js. It's upto them whether to use it or not.

If anyone calls me stupid because of using libraries, I'll be happy to be a stupid.