Get HTML content without comment lines using jquery

Take a 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 as shown above. My question is, is there any way out without comment?

+3


source to share


3 answers


You can create a clone and then remove all comment nodes from it (unless you want to change 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

+11


source


try the first selector like this



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

      

0


source


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/

0


source







All Articles