SoulieBaby
SoulieBaby

Reputation: 5471

using jquery contains inside a function?

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! :)

Upvotes: 2

Views: 3351

Answers (4)

brianc
brianc

Reputation: 1619

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
  }
 }
}

Upvotes: 1

ysth
ysth

Reputation: 98388

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.

Upvotes: 1

jebberwocky
jebberwocky

Reputation: 1089

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");

Upvotes: 1

Rebecca Chernoff
Rebecca Chernoff

Reputation: 22607

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")) {

Upvotes: 3

Related Questions