What is the difference between "querySelector" and "querySelectorAll"?

Asked

Viewed 778 times

1

I need some help to understand how the querySelector and the querySelectorAll, I’m used to using jquery selectors with the $(), but when I use the querySelector it returns me only the first element and if I use the querySelectorAll i can’t add events, so how do I have the same effect as a jquery selector using pure javascript?

1 answer

3


First of all querySelector and querySelectorAll are different. The querySelector returns the first element within the document and querySelectorAll returns a list of elements present in the document.

The way to add events using pure javascript is by using the addEventListener. The addEventListiner must receive two parameters, first the type of the event and second the action that must be performed when that event occurs.

document.querySelector("button").addEventListener("click", function(){
  alert("Olá")
});
<button>Click</button>

In the Example above, we select a button, when click(that the event we expect), we will perform a function that starts a alert.

document.querySelectorAll("button").forEach(function(btn) {
  btn.addEventListener("click", function(){
    alert("Agora com QuerySelectorAll");
  });
});
<button>Click</button>
<button>Click</button>

For you to apply the addEventListener in a list of elements you must interact this list, can do this with a foreach.

  • But what if I use the querySelectorAll to apply the addEventListner in all elements equal in jquery ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.