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: unable to find elements from jQuery object

I am fetching HTML string and I want to construct a jQuery object from it and then perform operations but I am getting undefined.

    var data = '<h1>Hi World</h1';
    var html = '<div id="rendered">'+data+'</div>';
    //var content = $($.parseHTML(html));
    var content = $.parseHTML(html);

    console.log($(content).find('#rendered').html()) // it says undefined

>Solution :

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

find() is used to look for child elements. #rendered is the parent node in the HTML structure you create, so find() doesn’t return anything. You need to use filter() instead as that includes the current node when searching.

Also note that $.parseHTML() isn’t required – jQuery does this automatically when you provide a HTML-formatted string to the jQuery object contructor.

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

console.log($(html).filter('#rendered').html())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
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