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?
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.
To get the attribute of a target element in JavaScript you would simply use: e. target. getAttribute('id');
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.
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 .
Try: onclick="markActiveLink(this);"
and
function markActiveLink(el) {
alert($(el).attr("id"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With