Bala
Bala

Reputation: 3638

How to see the source code of a particular html tag by onClick() javascript without showing its css?

Hi everyone, here am trying to display the source code of a particular div by onclick

javascript function. But the result am getting is , when i click on the div, am seeing the

whole source code though am trying to make only the particular source code of a div to get

displayed. anyone please highlight me what am doing wrong here..! and what to do to make

it work in the way its expected.

  <html>
    <head>
        <title></title>
    <script type="text/javascript">
    function viewsource(){
       var oldHTML = document.getElementById('para').innerHTML;
       var newHTML = "" + oldHTML + "";
       var newHTML = newHTML.replace(/</g,"&lt;");
       var newHTML = newHTML.replace(/>/g,"&gt;");
       var newHTML = newHTML.replace(/\t/g,"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        document.getElementById('para').innerHTML = newHTML;
    }
    </script>

    </head>

    <body>
    <p id='para'><strong>This is my <span style="border: 1px solid #ccc;">test text</span> to check if it works</strong></p> 
    <input type='button' onclick='viewsource()' value='View Source'/>
    </body>
    </html>

Additional notes:

In the above code, when the button is clicked, the paragraph tag with the id of para will display...but it shows its css too. I want to display only the html tag without the css style attribute.

I don't want the content using innerHTML but i want the whole div including with the div id.(eg.)<div id='softros'><img src='/images/bgrade.jpg' /></div>

Upvotes: 0

Views: 2215

Answers (2)

PiTheNumber
PiTheNumber

Reputation: 23542

You can get the HTML of the div using .innerHTML or .outerHTML but you need the encode it before you can display it. Otherwise the html gets renderd by the browser. In PHP you could use htmlencode javascript has no function for this but you could use this htmlencode.

Upvotes: 0

Mark Bramnik
Mark Bramnik

Reputation: 42461

have you considered to just use inside your java script handler :

document.getElementById(YOUR_DIV_ID_GOES_HERE).innerHTML

Upvotes: 2

Related Questions