Alex
Alex

Reputation: 68046

Can I update a property on all elements directly

For example:

var inputs = document.querySelectorAll('input[type="checkbox"]');

I want to set the checked to true on all inputs. Can this be done like in jQuery, without using a for loop?

Upvotes: 0

Views: 103

Answers (4)

Peter Featherstone
Peter Featherstone

Reputation: 8102

Using pure JavaScript you can use the querySelectorAll() function as below:

var checkboxes = document.querySelectorAll('input[type="checkbox"]');

for(var i=0; i<checkboxes.length; i++) {  checkboxes[i].checked = true; }

Unfortunately this doesn't avoid looping which I know you wanted to avoid and It also doesn't have perfect cross browser compatibility as can be checked here with IE 8 only being able to hook on to CSS 2.1 selectors and Pre IE8 not being supported at all but it's the best that can be done without using lots of code and avoiding jQuery.

I know you want to avoid jQuery but, if you change your mind you can try the following:

$('input[type="checkbox"]').attr('checked', 'checked')

This should hook on to any checkbox input and set its attribute to checked using the jQuery attr() function.

If this doesn't work try giving your checkboxes their own class name such as checkbox and try like as follows:

$('.checkbox').attr('checked', 'checked')

This would help with compatibility issues and would avoid looping but if you don't want to go the jQuery route then please ignore.

Upvotes: 1

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123473

without using a for loop

At some point, you're going to need some form of loop. Are you just hoping to abstract it?

NodeLists are Array-like, so you can call or apply methods from Array.prototype, including iterators like forEach(). An example from MDN:

Another approach without extending the DOM:

var forEach = Array.prototype.forEach;

var links = document.getElementsByTagName('a');
forEach.call(links, function(link){ // works in most browsers (please document here if you find browsers where it doesn't)
  link.style.color = '#0F0';
});

But note that even forEach() depends on a loop (while in this case).

Upvotes: 3

thefrontender
thefrontender

Reputation: 1842

querySelectorAll returns a NodeList. You will need to iterate over the list to change each item in it (jQuery loops over the entire collection too in the background using .each)

You can either use a loop (for, while, etc) or you could use the forEach method on the Array prototype

https://developer.mozilla.org/en-US/docs/DOM/NodeList#Workarounds

Upvotes: 4

Felix Kling
Felix Kling

Reputation: 816522

No, this cannot be done without some form of iteration over the nodes. jQuery iterates over the nodes as well, it just hides it from the user.

The closest that comes to jQuery-like style is using .forEach [MDN] in browser where it is supported:

[].forEach.call(inputs, function() {
    this.checked = true;
});

Upvotes: 3

Related Questions