-1

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 
Shoyeb Sheikh
  • 2,659
  • 2
  • 10
  • 19

1 Answers1

2

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>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • how does it work ? and what was wrong with my code ? – Shoyeb Sheikh Mar 07 '21 at 13:56
  • *how does it work* - same as you attempted, but jquery needs a "root" html element - in this case `
    ` you could just as easily do `$("
    " + your_string + "
    ")` - but your_string doesn't have a root, so won't parse correctly
    – freedomn-m Mar 07 '21 at 14:18