1

I have this part of a function that sets css properties on two buttons (update, save). I'm trying to minimize the lines of code and i'm looking for a more efficient way of setting css properties on multiple HTML elements rather than writing getElementById for every element. Is querySelectorAll suitable for use in this context?

//Chris

var css = {"backgroundColor": "red","textDecoration": "line-through"};
  for (var prop in css) {   
    document.getElementById("update").style[prop] = css[prop];
    document.getElementById("save").style[prop] = css[prop];
  }
6
  • There should be a dot after .style. Commented Mar 6, 2017 at 12:12
  • Yes, querySelectorAll is suitable for use in this context. Commented Mar 6, 2017 at 12:14
  • querySelectorAll suitable for use, but to set style you will have to iterate the result of querying and set style for each element in array Commented Mar 6, 2017 at 12:17
  • You should look at jsperf.com/style-versus-jquery-css/8 Commented Mar 6, 2017 at 12:21
  • 1
    Whoa, jsperf is back again, thanks @shubhamagrawal Commented Mar 6, 2017 at 12:27

3 Answers 3

1

Yes, querySelectorAll could be used in this context. Be aware that it isn't supported in IE8 or earlier. Check out the MSN docs for some quirks.

In addition, be aware that querySelectorAll returns an array like object (a non live NodeList) so you'll have to modify your code to work with such a structure:

var css = {"backgroundColor": "red","textDecoration": "line-through"}; 

var matched = document.querySelectorAll("#update, #save");
matched.forEach(function (c){
  c.style.backgroundColor css.backgroundColor;
  c.style.textDecoration = css.textDecoration;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for an informative answer and also for notyfing the compatibility issues. Luckily only users of IE10 or later will affected by this. I'll try something similar
Glad you found my answer useful :-)
1

I'd suggest the following method

var css = {"backgroundColor": "red","textDecoration": "line-through"};
var elements = document.querySelectorAll('#update, #save');
for (var prop in css) {
    elements.forEach(function (element) {
        element.style[prop] = css[prop];
    });
}

here the querySelectorAll is used with multiple selectors

Comments

0

Using document.querySelectorAll you could do it this way.

/*declare a css class*/

.button-css{"backgroundColor": "red","textDecoration": "line-through"};

/*in javascript you can do the following*/
var buttons=document.querySelectorAll(".buttons");

buttons.forEach(function(button){
  button.classList.add('button-css');
})

Comments

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.