August 31, 2012

jquery selector contains equals sign

Question by John Buckwell

I am using a jQuery selector to check for characters in href:

var param = "something";
$("a[href*="+param+"]").css("color", "red");

This works fine until “something” contains an = sign. Eg:

var param = "xkey=123";
$("a[href*="+param+"]").css("color", "red");

then I get no result. Anyone know a solution?

Answer by Starx

It is behaving that way becuase, at the end it will translate to ambiguous selector i.e. $("a[href*=xkey=123]") which indeed is invalid.

Escape the equal sign with \ infront and wrap the parameter part with a quote

var param = "xkey\=123";
$("a[href*='"+param+"']").css("color", "red");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!