Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get value of an attribute of the clicked element

<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?

like image 808
Omu Avatar asked Mar 05 '11 17:03

Omu


People also ask

How do you find the value of clicked elements?

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.

How do you get the ID of an element in JavaScript from a clicked?

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 do I get attributes from querySelector?

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.

What is the use of GET attribute?

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.


2 Answers

Original answer - 2011

$('li').click(function () {     alert($(this).data('val')); }); 

See DEMO.

Update - 2017

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.

like image 147
rsp Avatar answered Sep 17 '22 00:09

rsp


This should do the job:

$(document).ready(function() {    $('#langs li').click(function() {     alert($(this).attr('data-val'));   }); }); 

Have a look at the Docs

like image 34
sled Avatar answered Sep 19 '22 00:09

sled