so I have this HTML code where I hide the body of the website using
<style>
body{
display: none;
}
</style>
<body>
<p>Something..</p>
</body>
but now I want to remove this using Javascript without giving the body an ID or a class. As a solution I've tried the following but it is not working.
document.getElementsByTagName("body")[0].removeAttribute("style");
Any help is appreciated. Thanks.
If you want to remove the style tags added in your HTML, you have to select it using document.getElementsByTagName and call remove method to its nodes.
Working Fiddle
document.getElementsByTagName("style")[0].remove();
body {
display: none;
}
<p>Something..</p>
If you want to set style to the element
If you just want to set the display style of body tag, you can do this with javascript using.
document.getElementsByTagName("body")[0].style.display
More Generic Solution
const body = document.getElementsByTagName("body")[0];
const targetStyles = {
display: 'block',
}
Object.entries(targetStyles).forEach(([style, value]) => body.style[style] = value);
body {
display: none;
}
<p>Something..</p>
What is the issue with your script?
document.getElementsByTagName("body")[0].removeAttribute("style");
This script selects the body tag from HTML and removed the inline style added to the body. Its will work for below template, but not for your requirement.
document.getElementsByTagName("body")[0].removeAttribute("style");
<body style="background: blue;">
<p>Something..</p>
</body>
You can set document.body's display style property to unset:
document.body.style.display = "unset"
<style>
body {
display: none;
}
</style>
<body>
<p>Something..</p>
</body>