0

I have a page I'm coding but I'm new to Javascript. Due to an error in the page, I have to set the body,html element background color to transparent in order to achieve the look I want on the mobile page. I wish to achieve this through JavaScript to change as little CSS as possible from the original coding. After doing some research here:

How to get elements with multiple classes

This what I have so far:

var x = document.querySelectorAll('body, html');
x.style.backgroundColor = "transparent";

Unfortunately, this is raising an undocumented exception/error. The reason I suspect is that the syntax "('body, html')" is not correct in this case and is thus providing me with the wrong element or no element at all. My real issue with this problem is that I'm not actually looking for class names or IDs but for the body and HTML tags, which are top-level top level elements in the dom.

Any help anyone can be with this would be a huge aid to me.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Cui Bono
  • 13
  • 6
  • 4
    your whole question text could be skipped if you just posted the text of what you call `undocumented exception/error`. Error messages are important! – smnbbrv Jul 18 '18 at 05:16

3 Answers3

2

document.querySelectorAll will produce a NodeList of items, which is an iterable (not exactly an array but similar), therefore you will have to loop through the results like so:

var x = document.querySelectorAll('body, html');
for (var i = 0; i < x.length; i++) {
 x[i].style.backgroundColor = "transparent";
}
andriusain
  • 1,211
  • 10
  • 18
  • or a one-liner `document.querySelectorAll('body, html').forEach(x => x.style.backgroundColor = "transparent")` – smnbbrv Jul 18 '18 at 05:19
  • Thanks for the answer. Worked like a charm. Strange though, when I was trying to figure out the code I tried to alert x, but just got a strange bunch of nonsense. O_o Still, al least I know whats going on now. :) – Cui Bono Jul 18 '18 at 05:50
  • If you want to know more about the nature of x you could log it in the console and explore its properties: console.log('x', x); Note the first 'x' is just to let you know what you're logging in the console, otherwise you may not have a clue of what is what if there are many things being logged. – andriusain Jul 18 '18 at 05:52
0

You can also do:

[].forEach.call(
    document.querySelectorAll('body, html'),
    (x) =>  x.style.backgroundColor = "transparent"
);

[].forEach.call(
    document.querySelectorAll('body, html'),
    (x) => x.style.backgroundColor = "transparent"
);
caiovisk
  • 3,667
  • 1
  • 12
  • 18
0

You can do that separately in two lines of code. This is cross browser solution.

document.documentElement.style.backgroundColor = "transparent";
document.body.style.backgroundColor = "transparent";