jQuery contains() – May not do what you think it does

As I was writing some javascript I needed to determine if a string was contained within the value of an element.

So, I started out with the following:

var myValue = $(“#myElement”).val();

The I proceed to check if my specific string was in fact part of myValue. So I kept coding:

if (myValue.contains(“magicString”)){

alert(“Test”);

}

But I never got my “Test” alert message. Why?

Because contains didn’t do what I thought it would. It’s meant to be used with DOM elements. Once I read the documentation it all became clear.

To start contains requires two arguments and looks like: $.contains(container, contained). It verifies if the second element (second parameter) is a descendant of the first element (first parameter). Since it’s looking for a descendant, location doesn’t matter. As long as the second element contains the first element somewhere it will return true.

So now I still needed a way to see if my string was contained in myValue… so I did some research this time and came up with the following:

if (myValue.indexOf(“magicString”) > -1) {

alert(“Test”);

}

This time I got my test message. This is the closest thing javascript has built in to verify if a string is contained within a value. If the string exists in the value, indexOf will return the index of that string (which will be greater than 1) and thus we have a work around.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: