Get an Attribute from the Clicked Element With JavaScript

retrieve getAttribute of clicked element in javascript

Because this is the document object in your click handler, so you may want to check whether the click has happened in an image element

var getImageName = function() {  document.onclick = function(e) {    if (e.target.tagName == 'IMG') {      var image = e.target.getAttribute("src");      alert(image);    }  }}
getImageName()
<img id="a" src="//placehold.it/64X64&text=1" /><br><img id="a" src="//placehold.it/64X64&text=2" /><br>

Get an attribute from the clicked element with Javascript

.attr() is a jQuery method, In vanilla JavaScript you have to use getAttribute() to access the attribute:

e.target.getAttribute('data-element');

Array.from(document.getElementsByClassName('my_buttons_class')).forEach((button) => {  button.addEventListener('click', (e)=>{    e.preventDefault();    console.log(e.target.getAttribute('data-element'));          });});
<button class="my_buttons_class" data-element="some json">My button text</button>

Get attribute of clicked element using Javascript?

Instead of targetuse Event.currentTarget:

The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.

let attr = e.currentTarget.getAttribute('name');

let navLinks = document.querySelectorAll(".navbar .item");        navLinks.forEach(function(link){  link.addEventListener("click",function(e){    let attr = e.currentTarget.getAttribute('name');    console.log(attr); //logs null
//openPage(".home"); });});
<nav class="navbar">    <div class="container">        <div name="home" class="item active">            <div><img src="img/icons/home1.png"></div>            <div>Home</div>        </div>        <div name="faq" class="item">            <div><img src="img/icons/faq2.png"></div>            <div>FAQ</div>        </div>         <div name="calc" class="item cta_calc">            <div><img src="img/icons/dash1.png"></div>        </div>         <div name="about" class="item">            <div><img src="img/icons/info3.png"></div>            <div>About</div>        </div>         <div name="contact" class="item">            <div><img src="img/icons/info2.png"></div>            <div>Contact</div>        </div>    </div>       </nav>

Why can't I get the attribute of the clicked element with this JavaScript arrow function?

You get undefined because you didn't passed the event object. change:

onclick="changeStatus()"

to:

onclick="changeStatus(event)"

Also note that using inline handlers is not a good practice. if you care about good practices, don't use inline event handlers. Instead select the element in javascript and attach the click event listener to it:

const btns = document.querySelectorAll('.btn')
btns.forEach(btn => btn.addEventListener("click", e => {
let car = cars[btn.dataset.row];
console.log(car);
}));

get value of an attribute of the clicked element

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.

How to return an attribute of clicked element in react?

You can access the title via currentTarget

try this:


function App () {
return (
<button
title={'foo'}
onClick={myFunction}
>
click me
</button>
)
}

function myFunction(e) {
alert(e.currentTarget.title);
}

How to get data attribute of element when click on it or it child

Try to use closest by your child tag instead of dataset.

document.querySelector('table').addEventListener('click', (e) => {  console.log(e.target.closest("td").dataset.item);})
td {  padding: 8px;  border: 1px solid black;  background-color: blue;}
span { background-color: red; padding: 4px;}
<table>  <tr>    <td data-item="item1"><span>1</span></td>    <td data-item="item2"><span>2</span></td>    <td data-item="item3"><span>3</span></td>    <td data-item="item4"><span>4</span></td>    <td data-item="item5"><span>5</span></td>  </tr></table>

How can I retrieve the attribute of a clicked element with jQuery?

You should use the .attr function:

$(".adsw-attribute-option > .meta-item-text").on("click", function () {
$(this).attr('data-value');
});

It's important you don't use an arrow function because you can't call this when using an arrow function.

get data attribute of a clicked element in a linked function

By it's self, e.target is only an element and will not be able to have .attr() function. This should show in your Console.

Also, you do not pass any arguments to the function. Consider the following.

function test(e) {  if (e == undefined) {    console.log("Event is Undefined");    return false;  }  let tg = $(e.target).data('tg');  console.log(tg); // error - target is undefined}
$("#btn-1").on('click', function(event) { let fn = $(this).data('fn'); window[fn](event);});$("#btn-2").on('click', function(event) { let fn = $(this).data('fn'); window[fn]();});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn-1" data-tg='imgt' data-fn='test'>Test 1</button><button id="btn-2" data-tg='imgt' data-fn='test'>Test 2</button>


Related Topics



Leave a reply



Submit