admin管理员组文章数量:1129006
I'm currently trying to write some JavaScript to get the attribute of the class that has been clicked. I know that to do this the correct way, I should use an event listener. My code is as follows:
var classname = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
classname.addEventListener('click', myFunction(), false);
I was expecting to get an alert box every time I clicked on one of the classes to tell me the attribute but unfortunately this does not work. Can anyone help please?
(Note - I can quite easily do this in jQuery
but I would NOT like to use it)
I'm currently trying to write some JavaScript to get the attribute of the class that has been clicked. I know that to do this the correct way, I should use an event listener. My code is as follows:
var classname = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
classname.addEventListener('click', myFunction(), false);
I was expecting to get an alert box every time I clicked on one of the classes to tell me the attribute but unfortunately this does not work. Can anyone help please?
(Note - I can quite easily do this in jQuery
but I would NOT like to use it)
- 3 There's a problem with the code that's adding the event listener. addEventListener takes the event name ('click'), reference to the function (not the result of the function as it is now by calling myFunction() with parens) and a flag to indicate event bubbling. The addEventListener call should look like: elem.addEventListener('click', myFunction, false) and classname is a NodeList type. Need to loop over all the elements and attach the listener to each one in the list. – Joey Guerra Commented Mar 23, 2015 at 3:03
8 Answers
Reset to default 611This should work. getElementsByClassName
returns an Array-like object (see below) of the elements matching the criteria.
var elements = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction, false);
}
jQuery does the looping part for you, which you need to do in plain JavaScript.
If you have ES6 support you can replace your last line with:
Array.from(elements).forEach(function(element) {
element.addEventListener('click', myFunction);
});
Note: Older browsers (like IE6, IE7, IE8) don´t support getElementsByClassName
and so they return undefined
.
Details on getElementsByClassName
getElementsByClassName
doesn't return an array, but a HTMLCollection
in most, or a NodeList
in some browsers (Mozilla ref). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array (meaning other methods that can be performed on an Array cannot be performed on these types).
Thanks to user @Nemo for pointing this out and having me dig in to fully understand.
With modern JavaScript it can be done like this:
const divs = document.querySelectorAll('.a');
divs.forEach(el => el.addEventListener('click', event => {
console.log(event.target.getAttribute("data-el"));
}));
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
<style>
.a {
background-color:red;
height: 33px;
display: flex;
align-items: center;
margin-bottom: 10px;
cursor: pointer;
}
.b {
background-color:#00AA00;
height: 50px;
display: flex;
align-items: center;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="a" data-el="1">1</div>
<div class="b" data-el="no-click-handler">2</div>
<div class="a" data-el="3">11</div>
</body>
</html>
- Gets all elements by class name
- Loops over all elements with using forEach
- Attach an event listener on each element
- Uses
event.target
to retrieve more information for specific element
You can use the code below:
document.body.addEventListener('click', function (evt) {
if (evt.target.className === 'databox') {
alert(this)
}
}, false);
* This was edited to allow for children of the target class to trigger the events. See bottom of the answer for details. *
An alternative answer to add an event listener to a class where items are frequently being added and removed. This is inspired by jQuery's on
function where you can pass in a selector for a child element that the event is listening on.
var base = document.querySelector('#base'); // the container for the variable content
var selector = '.card'; // any css selector for children
base.addEventListener('click', function(event) {
// find the closest parent of the event target that
// matches the selector
var closest = event.target.closest(selector);
if (closest && base.contains(closest)) {
// handle class event
}
});
Fiddle: https://jsfiddle.net/u6oje7af/94/
This will listen for clicks on children of the base
element and if the target of a click has a parent matching the selector, the class event will be handled. You can add and remove elements as you like without having to add more click listeners to the individual elements. This will catch them all even for elements added after this listener was added, just like the jQuery functionality (which I imagine is somewhat similar under the hood).
This depends on the events propagating, so if you stopPropagation
on the event somewhere else, this may not work. Also, the closest
function has some compatibility issues with IE apparently (what doesn't?).
This could be made into a function if you need to do this type of action listening repeatedly, like
function addChildEventListener(base, eventName, selector, handler) {
base.addEventListener(eventName, function(event) {
var closest = event.target.closest(selector);
if (closest && base.contains(closest)) {
// passes the event to the handler and sets `this`
// in the handler as the closest parent matching the
// selector from the target element of the event
handler.call(closest, event);
}
});
}
=========================================
EDIT: This post originally used the matches
function for DOM elements on the event target, but this restricted the targets of events to the direct class only. It has been updated to use the closest
function instead, allowing for events on children of the desired class to trigger the events as well. The original matches
code can be found at the original fiddle:
https://jsfiddle.net/u6oje7af/23/
All the above-mentioned answers are correct and I just want to demonstrate another short way
document.querySelectorAll('.classname').forEach( button => {
button.onclick = function () {
// rest of code
}
});
Yow can use querySelectorAll to select all the classes and loop through them to assign the eventListener. The if condition checks if it contains the class name.
const arrClass = document.querySelectorAll(".className");
for (let i of arrClass) {
i.addEventListener("click", (e) => {
if (e.target.classList.contains("className")) {
console.log("Perfrom Action")
}
})
}
Also consider that if you click a button, the target of the event listener is not necessaily the button itself, but whatever content inside the button you clicked on. You can reference the element to which you assigned the listener using the currentTarget property. Here is a pretty solution in modern ES using a single statement:
document.querySelectorAll(".myClassName").forEach(i => i.addEventListener(
"click",
e => {
alert(e.currentTarget.dataset.myDataContent);
}));
Here's a different approach for many DOM elements with the same class name by selecting path key in the eventListener object.
Add an event listener to the immediate parent class wrapping all the child elements with the same class and get the path by selecting the first key in the event object.
E.g say you want to edit table cells of a table
//Select tbody element & add event listener
let tbody = document.querySelector('tbody');
tbody.addEventListener("click", function(e,v) {
// Get the clicked cell
let cell = e.path[0];
// Get the current cell value
let cellValue = cell.innerHTML;
//Rest of code goes here
}
本文标签: JavaScript click event listener on classStack Overflow
版权声明:本文标题:JavaScript click event listener on class - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736713356a1949065.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论