Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JQuery: How to fetch the remaining HTML after removing elements?

I am having a very hard time using jQuery on a custom HTML object. I am searching an element and removing it and after that I need the remaining HTML but I am unable to do it. My code is below:

Ideally it should return <div id="rendered"></div> only.

var data = '<h1 id="H9">Hi World</h1';
var html = '<div id="rendered">' + data + '</div>';

console.log($(html).find('#H9').length)
$(html).find('#H9').remove()
$('#view').html($(html).filter('#rendered').html()) // it shows h9 is there
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div id="view"></div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You did not remove it from html, but from the unused object created by $(html)

Also you missed a > in </h1

var data = '<h1 id="H9">Hi World</h1><h2>Keep this</h2>';
var html = '<div id="rendered">' + data + '</div>';

const $html = $(html); // now we have a jQuery object
$html.find('#H9').remove(); // remove the #H9
console.log($html.filter('#rendered').prop("outerHTML") )
$('#view').html(
  $html.filter('#rendered').prop("outerHTML") // insert the div
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div id="view"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading