<ul id='langs'> <li data-val='en'>english</li> <li data-val='fr'>francais</li> <li data-val='it'>italiano</li> </ul>
when the user clicks on any of these <li>
I want to alert()
it's data-val attribute value
anybody knows how?
Another way to get the element we clicked on in the event handler is to get it from the event object which is the first parameter in the event handler function. And the following JavaScript code: const onClick = (event) => { console. log(event.srcElement.id); } window.
The buttonPressed() callback function will have a returned event object which has all the data about the HTML element that is clicked on. 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 it works: First, select the link element with the id js using the querySelector() method. Second, get the target attribute of the link by calling the getAttribute() of the selected link element. Third, show the value of the target on the Console window.
The getAttribute() method is declared in the WebElement interface, and it returns the value of the web element's attribute as a string. For attributes having boolean values, the getAttribute() method will return either true or null.
$('li').click(function () { alert($(this).data('val')); });
See DEMO.
Keep in mind that if you want to use the ES6 arrow function syntax, you cannot use this
and you need to use e.currentTarget
instead, where e
is the event object passed as the first parameter to the event handler:
$('li').click(e => alert($(e.currentTarget).data('val')));
See DEMO.
This should do the job:
$(document).ready(function() { $('#langs li').click(function() { alert($(this).attr('data-val')); }); });
Have a look at the Docs
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