user2510841
user2510841

Reputation: 49

How to remove all elements inside <style> tag in JavaScript?

So as per my title question, how to remove all elements inside style tag.

I have style tag inside the body. I am just retrieving the HTML code.

<body>
 <style>
    td {...};
    a {....};
 </style>
<body>

I have remove the style tag alone. But not the elements inside it. I can still retrieve the:

<body>
    td {...};
    a {....};
<body>

I also need to remove the

td {...};
a {....};

Thanks in advance!

Upvotes: 0

Views: 3269

Answers (3)

ElijahFowler
ElijahFowler

Reputation: 66

If your project is using jQuery you can easily remove the content of the style tag with a really short bit of script:

$(document).ready(function () {
    $('style').html("");
});

Here's a jsFiddle showing that it works.

Upvotes: 0

markasoftware
markasoftware

Reputation: 12652

You're trying to remove an HTML element. You can do it like this, assuming that the tag is the only one in the document

(var styleElt=document.getElementsByTagName('style')[0]).parentNode.removeChild(styleElt)

Upvotes: 0

Matt Bryant
Matt Bryant

Reputation: 4961

If you're trying to remove all css elements in the body, you could do something like:

var x = document.body.getElementsByTagName("style");
for (var i = x.length - 1; i >= 0; i--)
    x[i].parentElement.removeChild(x[i]);

If you are trying to remove just the first one in the body:

var x = document.body.getElementsByTagName("style");
if (x.length)
    x[0].parentElement.removeChild(x[0]);

Edit: Removed method using map. Crazy Train correctly pointed out that it probably wouldn't work.

Upvotes: 3

Related Questions