finding html element in jquery string

I have this code where I am trying to find number of elements in a string using jquery,

var s = 'assasdsa<img src="http://localhost/cc/public/img/smileys/flushed face.png">sdsdajjk';  
var k = $(s).find('*'); 
console.log(k.length);

It gives an error though,

jquery-3.5.1.min.js:2 Uncaught Error: Syntax error, unrecognized expression: assasdsa<img src="http://localhost/cc/public/img/smileys/flushed face.png">sdsdajjk 

Answer

Append the string to an element and find within that element instead

var s = 'assasdsa<img src="http://localhost/cc/public/img/smileys/flushed face.png">sdsdajjk';  
var k = $('<div>').append(s).find('*'); 
console.log(k.length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Leave a Reply

Your email address will not be published. Required fields are marked *