Get ID of clicked on element in function

I want to get the ID of an element I click on. I put the function in the onclick element, like this:

<a id="myid" class="first active" onclick="markActiveLink();" href="#home">Home</a>

And this is in the function:

function markActiveLink() {   
    alert($(this).attr("id"));
}

This doesn't work, as it says it isn't defined. Does it really forget about the ID, do I have to type it in the onclick?

Answers:

Answer

Try: onclick="markActiveLink(this);" and

function markActiveLink(el) {   
    alert($(el).attr("id"));
}
Answer

why using an inline handler? Move to unobtrusive js

$(document).ready(function(){
  $('#myid').bind('click', function(){
     alert($(this).attr('id'));
  });
});
Answer

You have to pass the element to the function. JS itself isn't smarter than you :)

html:

<a id="myid" class="first active" onclick="markActiveLink(this);" href="#home">Home</a>

js:

function markActiveLink(e) {   
    alert(e.id);
}
Answer

Do not use $(this) because it does accidentally return the element you added the bind. When you click on an inner element, it also returns the outer element.

<div id="outer">
    <div id="inner">

    </div>
</div>

You better use the following appearance:

$("#outer").bind('click', function(e) {

    if(e.target.id === "inner")
    {
        alert("you clicked the inner element");
    }
    else
    {
        alert("you clicked the outer element");
    }
});

You can find a fiddle here: http://jsfiddle.net/vqab7jdo/1/

Answer

I try all the ways, spend almost 2 hours and finally found the best way I prefer try it:

< div onclick="div_Clicked(this.id)" id="some"/>

    function div_Clicked(itemName) { alert(itemName); }

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.