1

(with pure javascript) how I can connect an event to all the elements of a certain tag or a certain class? Using "querySelector", they select only one item (the first), while using "getElementByTagName" or "getElementByClassName" not I select none (I display an error in the console).

Thanks so much.

//byCssSelector - CLASS
document.querySelector(".myClass").addEventListener("click", function() { alert("ok"); });
// byCssSelector - TAG
document.querySelector("section").addEventListener("click", function() { alert("ok"); });

//byClass
document.getElementByClassName("myClass2").addEventListener("click", function() { alert("ok"); });
//byTag
document.getElementByTagName("div").addEventListener("click", function() { alert("ok"); });
<br><b>querySelector:</b><br>
<p class="myClass">1) querySelector(".class")</p>
<section>2) querySelector("[tag]")</section>
<br><b>Tag/Class-name:</b><br>
<span class="myClass2">3) getElementByTagName</span>
<div>4) getElementByClassName</div>

3 Answers3

2

querySelector only returns the first element it finds. You should user querySelectorAll, which returns a list of elements matching the tag. You can then user forEach, to loop through the elements and attach a listener to every one of them.

document.querySelectorAll('.myClass').forEach(function (el) {
  el.addEventListener('click', function() {
    alert('ok');
  });
});

NodeList.forEach is a new feature and is not supported in all browsers. You can check compatibility here. If you wish to support them, you will have to use for loop or convert nodeList to array.

You can use [].slice.call for it. If you are using ES6/ES2015, you can even look into Array.from

Rajesh
  • 24,354
  • 5
  • 48
  • 79
Gregor Menih
  • 5,036
  • 14
  • 44
  • 66
1

while using "getElementByTagName" or "getElementByClassName" not I select none (I display an error in the console).

There are 2 mistakes

  • It should be getElementsByTagName, not getElementByTagName
  • getElementsByTagName returns a live collection of nodes, not a single element.

Make it

var x = Array.prototype.slice.call(document.getElementByClassName("myClass2"));
x.forEach( function(el){
  el.addEventListener("click", function() { alert("ok"); });
});
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

.querySelector, as per MDN,

Returns the first Element within the document that matches the specified group of selectors.

var divs = document.querySelector('.content');
console.log(divs)
<div class="content">1</div>
<div class="content">2</div>
<div class="content">3</div>
<div class="content">4</div>

Where as what you are looking for is .querySelectorAll.

Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.

var divs = document.querySelectorAll('.content');
console.log(divs)
<div class="content">1</div>
<div class="content">2</div>
<div class="content">3</div>
<div class="content">4</div>

Once you have the list, you can refer following link to loop over nodeList

A useful reference: querySelector and querySelectorAll vs getElementsByClassName and getElementById

Community
  • 1
  • 1
Kevin
  • 1,219
  • 1
  • 16
  • 34
  • This should have been a comment – Rajesh Nov 02 '16 at 13:52
  • 1
    So, the answer to his question should be a comment? Just because his problem is really easy to fix doesn't make it necessary to be a comment. – Kevin Nov 02 '16 at 13:53
  • 1
    First its an obvious duplicate and I'll be marking it as one. You do not have enough rep as of now, but please when you have, mark questions as duplicate instead of answering them. Secondly, this is not an answer. Answer has explanation of what is wrong or what can be improved with code samples and possible reference links. Basically, if someone a year later reads this answer, he/she should learn something from it. – Rajesh Nov 02 '16 at 14:01
  • I follow what you're saying and can agree with it partially (about the duplicate part), but I am pointing out what his mistake is and how it can be improved, am I not? – Kevin Nov 02 '16 at 14:03
  • I have updated your answer. Please check if it conveys the same message. If not, please revert it. – Rajesh Nov 02 '16 at 14:15
  • Of course adding more information and references only makes the answer better. It's only up to you how wide you're making your answer... You could write a book as an answer, but would that help more than just the few rules that help him out with his question? I would know what to choose... – Kevin Nov 02 '16 at 14:21