Return an array of html elements with javascript

1

I'm trying to do the following:

elementos = function(param){
       return document.querySelectorAll(param)
}

elementos('.link').onclick=function(){
       //Codigo
}

Notify me error.

What I want to do more exactly is something similar to the jquery method to select multiple selectors: $ (". a, # button")

What is missing or how can I do it?

    
asked by Benjamin 25.09.2017 в 06:54
source

1 answer

1

The method document.querySelectorAll(param) returns a list of elements that comply with the query, so you can not simply use .click on your result as in jQuery, you have to go through each of the elements and assign the function click one by one, this you can do with forEach .

document.querySelectorAll(".link").forEach(function(el) {
  el.onclick = function() {
    alert("Hola Mundo");
  }
});
<a class="link">Enlace 1</a>
<a class="link">Enlace 2</a>
<a class="link">Enlace 3</a>
<a class="link">Enlace 4</a>
    
answered by 25.09.2017 в 07:10