Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to test if string contains HTML markup

I want to test if a string has html tags in it.

html = "<p class=\"c\">some <span>conten<b class=\"i\">t</b></span><p><p>more content</p><p><i>important</i>";

I would think that using either find() or has() would help me do this, but it's not working.

$(html).find("p") //[]
$(html).has("p")  //[]

And I get confusing results if I experiment.

$(html).has("p") //[]
$(html).has("*") //array of <p> elements and children
$(html).has("*") == true //false
$(html).has("*").length == true //false ??

Why can't I use any of these methods to see if my string contains HTML markup?

Thanks

like image 277
1252748 Avatar asked Dec 19 '22 16:12

1252748


1 Answers

Both .has() and .find() operate on the given element's children nodes. To test the element itself, use .is():

$(html).is('p');   // true
$(html).is('div'); // false
$(html).is('*');   // true

... although I'm rather sceptical about the usefulness of the latter, as it doesn't test specifically for HTML elements. So this...

var someMarkup = '<foo"bar"zzz>';
$(someMarkup).is('*');

... is also true. And if you omit the last > in this expression, you won't even reach is:

var noHtmlJustLt = '<';
$(noHtmlJustLt).is('*'); // Error: Syntax error, unrecognized expression: <

... so you have to wrap this into try-catch block.


To be honest, I'd probably solve the whole task (check whether or not a string has some rogue markup) with a different approach: escape the original text with a common trick...

var newHtml = $('<div></div>').html(html).text();

... then compare it with original html contents. If there's no markup symbols, they should be equal.

like image 92
raina77ow Avatar answered Dec 24 '22 02:12

raina77ow