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>
CodePudding user response:
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>