Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get HTML Content without comment lines using jquery

Tags:

html

jquery

css

Look at the following code.

HTML:

<div>
  <p>sdfsdfsfsf</p>
  <!--<p>testing</p>-->
</div>

JQUERY

$(document).ready(function(){
   alert($("div").html());
});

OUTPUT

<p>sdfsdfsfsf</p>
<!--<p>testing</p>-->

As I know it will give the output like above only. My Question is, Is there anyway we can get the output without the commented lines?

like image 615
Suresh Ponnukalai Avatar asked Oct 26 '25 06:10

Suresh Ponnukalai


1 Answers

You can create a clone and then remove all the comments nodes from it(if you don't want to modify the original dom)

$(document).ready(function () {
    var $clone = $("div").clone();
    $clone.contents().contents().addBack().filter(function () {
        return this.nodeType == Node.COMMENT_NODE;
    }).remove();
    console.log($clone.html());
});

Demo: Fiddle

like image 78
Arun P Johny Avatar answered Oct 28 '25 21:10

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!