views:

29

answers:

4

Hi all,

I'm trying to use the jquery :contains (or .contains()) selector inside a function, however I can't seem to get it to work.

Basically I'm passing a string to a function and I want to check the variable if it contains X, do something else do something else. If that makes sense.

Here's my code.

function checkMe(myVar) {
  if ($(myVar).contains("foo")) {
    //do something
  } else {
    //do something else
  }
}

and my call to the function:

checkMe("/foo/bar");

But it's not working. Any help would be appreciated! :)

+1  A: 

The jQuery contains function checks if a dom node contains another dom node. What you are wanting to do is just check to see if a string is contained inside another. You could do a simple regex search for this.

Try this instead:

if (myVar.match("foo")) {
rchern
+1  A: 

do you have to use jquery? what about something like this?

function checkMe(myVar) {
  if (myVar.indexOf("foo") > -1) {
    //do something
  } else {
    //do something else
  }
 }
}
bluevoodoo1
Why call toString on an object that is already a string?
rchern
you're absolutely correct (I'll edit)
bluevoodoo1
+1  A: 

hi just check the jquery api http://api.jquery.com/jQuery.contains/ , jquery.contains is applied to DOM element. if you want to do string contains, try:

/foo/i.test("foo/bar");
jebberwocky
+1  A: 

contains checks if one DOM element contains another.

For what you want, you don't need jQuery at all:

function checkMe(myVar) {
  if (myVar.indexOf("foo") >= 0) {
    //do something
  } else {
    //do something else
  }
}

indexOf will return -1 if "foo" is not found in the passed string; otherwise it returns the index in the string where "foo" was found.

ysth