Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialGreg Schudel
4,090 PointsHow do I use Javascript to remove all CSS styles in a HTML doc?
Here is what I have so far
loop(document);
function loop(node){
// do something with the node here
var nodes = node.childNodes;
for (var i = 0; i < nodes.length; i++){
if(!nodes[i]){
continue;
}
if(nodes[i].childNodes.length > 0){
let elements = loop(nodes[i]);
// remove attributes
elements.removeAttribute('');
}
}
}
But I keep on getting an error after the elements.removeAttribute, why??? What am I doing wrong?
1 Answer
Steven Parker
231,269 PointsThe "elements" variable is being set to the result of a recursive call to "loop", but "loop" doesn't return anything, so "elements" will always be undefined. Applying the "removeAttribute" method to an undefined variable produces the error.
There are several other issues here as well, including:
- "removeAttribute" only removes the attribute named by the argument, passing a blank will do nothing
- "removeAttribute" works on elements, but not all nodes are elements
- removing all attributes will have serious side effects (such as links not working)
And not all CSS relies on attributes, so even if this worked, the CSS that doesn't involve "style" or "class" attributes would not be affected.
It would be more effective, and avoid side-effects, to simply remove the lines that load CSS from the HTML.