Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 271
skerit Avatar asked Jun 01 '10 19:06

skerit


People also ask

How do you get the ID of a clicked element?

To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.

How do I find my e Target ID?

To get the attribute of a target element in JavaScript you would simply use: e. target. getAttribute('id');

What is click () method?

The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.

How do you show an element when a button is clicked?

To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .


1 Answers

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

function markActiveLink(el) {   
    alert($(el).attr("id"));
}
like image 142
No Surprises Avatar answered Sep 28 '22 11:09

No Surprises