shobhonk
shobhonk

Reputation: 656

jQuery contains selector and special char

I am having a bit of trouble using jQuery contains selector;

Consider the following html and jquery to check if an element contains certain text.

For example HTML:

<div>welcome :)</div>

jQuery Javascript:

$('div:contains("welcome :)")').length

If I run the above JS code for that HTML. It does not return 1 as it should.

However the following works as expected

$('div:contains("welcome")').length

Any suggestion how to accommodate for special characters like brackets or colon etc?

Upvotes: 2

Views: 572

Answers (1)

Prashant
Prashant

Reputation: 702

I think this might be because of escape characters used in JQuery selector. You can use '\' character before the escape characters like ':' to resolve the problem. Also for general approach below function can be used.

function jqescape(str) { return str.replace(/[#;&,\.\+\*~':"!\^\$\[\]\(\)=>|\/\\]/g, '\\$&'); }

I tried for below expression it gave me result as expected:

$('div:contains("welcome \:")').length

Upvotes: 3

Related Questions