2

With jquery, I've got the following code:

$('a[data-hello]').click(function(){ = That select all "a" elements with "data-hello".

I'm trying to make this with raw Javascript. I stop here:

document.querySelectorAll("data-hello").onclick = function() {

(btw, theres a way to select all the A elements with data-hello and not all with data-hello? o.O)

But querySelectorAll returns a Array. Because of this, it only works if I determine a position. This way:

document.querySelectorAll("data-hello")[5].onclick = function() {

But I want ALL ELEMENTS, not specific elements, like with jQuery. I cant use jQuery.

It is so simple with Jquery :( I must make a "for" to wade through all the positions in JS? Is this necessary? sorry I do not understand...


What I want to do:

I want to get the data attribute value of the element that is clicked. I use this for this inside the function and, then, I applied another function that add a class in a specific element. Basically, there is buttons with classes in data attribute value. This classes will be applied to a specific element.

4
  • "But querySelectorAll returns a Array." - No it doesn't, it returns a NodeList. (Which yes, you would then have to loop through - which is what jQuery methods like .click() do behind the scenes.) Commented Jan 5, 2014 at 0:19
  • And what's the difference between a nodelist and array? :S Commented Jan 5, 2014 at 0:20
  • The difference between an Array and a NodeList? Well, the main difference that you need to know about is that a NodeList doesn't have Array methods like .pop(), .forEach(), etc. (A NodeList is an array-like object, so you can use some array methods via Array.prototype and .call() or .apply().) Commented Jan 5, 2014 at 0:22
  • Unfortunately, NodeList isn't a fully-fledged Array, which caught me out. This Mozilla Developer Network (MDN) article explains it very well. Btw, googling mdn <html|css|javascript term> is a great way to begin debugging - I do so thousands of times a day =) Commented Jan 5, 2014 at 0:25

3 Answers 3

3

Put the array (actually a NodeList) of elements in a variable and loop through them to set the event handler on each of them. That's what the jQuery methods do to apply something to all elements in a jQuery object. There is no way around the loop, with jQuery it's just hidden within the methods. You can use the same selector syntax as in jQuery with querySelectorAll.

var arr = document.querySelectorAll("a[data-hello]");
var f = function() {
  // do something
};
for (var i = 0; i < arr.length; i++) {
  arr[i].onclick = f;
}
Sign up to request clarification or add additional context in comments.

Comments

1

querySelectorAll accepts a string of comma-separated CSS selectors, just like jQuery, so you can give it the same string: 'a[data-hello]'.

The difference between native and jQuery that you are running into is in calling methods on the elements returned. jQuery returns a jQuery object, which has methods that often loop over all the elements, .click() being one such methods. You need to replicate that with the array of elements that querySelectorAll is returning by looping over the array and applying the same handler to each element's onclick property.

Try this:

var myElements = document.querySelectorAll("a[data-hello]");
Array.prototype.forEach.call(myElements, function (element) {
    element.onclick = function () {
        // Your onclick handler code goes here.
        console.log('clicked', element);
    };
});

6 Comments

NodeList has no method forEach.
Right you are - forgot about that! I use abstraction libraries like lodash so regularly. Fixed it now =)
@SergeiZahharenko Thanks! Do you mean this bit? Array.prototype.forEach.call
Wow! So different.. Thank you, Henry, really! Thanks for explaining too! Happy new year!
Note: The forEach method doesn't exist in older browsers, like IE8.
|
0

as simple as that:

var dataElems = document.querySelectorAll("[data-hello]")
for (var i=0;i<dataElems.length;i++) { 
    dataElems[i].onclick = function(i,v) {
        alert(this.innerHTML)        
    }
}

example http://jsfiddle.net/acrashik/W86k8/

3 Comments

This dont works for me. "But querySelectorAll returns a Array. Because of this, it only works if I determine a position."
@PedroMelo you know you can just iterate through each element, which is what jquery does. document.querySelectorAll("[data-hello]").forEach(function(v) { v.onclick = function() {}});
@DarrenKopp Unfortunately your code won't work, for the same reason mine didn't at first: forEach isn't a method of NodeList, which querySelectorAll returns. It's a sorry state of affairs for chaining methods =(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.