Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13978

Get HTML Content without comment lines using jquery

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?

Upvotes: 4

Views: 1470

Answers (4)

Oleg
Oleg

Reputation: 7387

Regex works quite fine and efficient for this purpose:

$html.html().replace(/<!--.*-->/g, '')

Upvotes: 0

Rochak Chauhan
Rochak Chauhan

Reputation: 70

use .text() method of jQuery

    <div id="anything">
    <p>Any text here...</p>
    <!--<p>testing</p>-->
</div>
$(document).ready(function () {
    var t=$("#anything").text();
    console.log(t);
});

Demo: https://jsfiddle.net/6w1nr8km/2/

Upvotes: 0

vitally
vitally

Reputation: 377

try the first selector like this

<script>
$(document).ready(function(){
   alert($("div > p:first").html());
});
</script>

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

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

Upvotes: 11

Related Questions