tags:

views:

285

answers:

2

Can anyone tell me how to write javascript code that removes everything after the html tag.

I have the following file:

<html>
<head>
<script>
// my script
</script>
</head>
<body>
Some text
</body>
</html>
<script>
</script>

Rendered output must not contain the last script (or any other) tag.

+3  A: 

The problem is that in the DOM, outside of HTML there is nothing. Your closing </html> gets moved to account for the badly formatted HTML. Here is how firebug shows your example.

In firebug

This means that from javascript, there is no way to know which markup was after the html.

rq
Its still possible to do what he wants.
Jonathan Czitkovics
Well I should thank you as your answer lead me to my answer as I did not know this.
Jonathan Czitkovics
+3  A: 

This code waits for the page to load and then removes all tags after the </html> try it with firebug and you will see. You need to create a place holder as such in this example <div id="last"></div> after your last tag and then it removes the rest of the tags.

<html>
    <head>
        <script type="text/javascript">
        window.onload=function()
        {
        var body=document.getElementsByTagName('body')[0];
        var found=false;
        var cur=0;
        for(var i=0; i<body.childNodes.length; i++)
        {
            if(body.childNodes[i].id=='last')
            {
                cur=i;
                found=true;
            }
            else if(found && i>cur+1)
            {
                body.removeChild(body.childNodes[i]);
            }
        }
        }
    </script>
    </head>
    <body>
       Some text
       <div id="last">

       </div>
    </body>
</html>
<p>
Im not gonna show
</p>
<input/>
<script>
</script>
<b>
</b>

Don't forget to scroll! Enjoy!

Oddly enought the formating of code here is not functioning right. Its probably my fault.

Edit renamed my variable to body

Jonathan Czitkovics
if the "<p>" element is placed outside the "<html>" element, how can it be considered a "child element" of that element? This is semantically confusing. Although your solution might work (I've not tested it), I don't think it relies on standards :(
XpiritO
Heh, fair enough! You still need to mark the end of the *real* html though. I guess the guy wanted this to remove adverts or similar on free hosting so this might well work.
rq
@ XpiritO The reason why its a child element is that modern browsers as rq said place the tags in the body. I took this to my advantage and removed them after the div id="last" placeholder I added. Actually my variable `html` is actually the body tag, sorry for the bad naming.
Jonathan Czitkovics
renamed my variable to body.
Jonathan Czitkovics