0

Im trying to add a class to another element if an element contains text.

So let's say I have a <td> classified as vCSS_breadcrumb_td. How can I check is the <td> contains a word, and if it does contain that word, add a class to an <a> classified is nav1.

I know that I could probably make use of the :contains selector, I just don't know how to write an if statement

henryaaron
  • 6,042
  • 20
  • 61
  • 80
  • [Read about `if` statements in the MDN JavaScript Guide](https://developer.mozilla.org/en/JavaScript/Guide/Statements#if...else_Statement). – Felix Kling Jan 08 '12 at 22:24
  • http://stackoverflow.com/questions/902597/jquery-checking-to-see-if-div-contains-text-then-action Check out this question, seems similar. – Christopher Marshall Jan 08 '12 at 22:25

3 Answers3

0
if ($('.vCSS_breadcrumb_td:contains("word")').length) {
    $('.nav1').addClass('class');
}

You need to check the length property, since jQuery always returns an Array-like object.

David Hellsing
  • 106,495
  • 44
  • 176
  • 212
0

How about

if ($("td.vCSS_breadcrumb_td").text().length)
    $("a.nav1").addClass("someClass");
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0
if ($('#field > div.field-item:contains("someText")').length > 0) {
    $("#somediv").addClass("thisClass");
}

Copied from Jquery: Checking to see if div contains text, then action and posted as answer

Community
  • 1
  • 1
Christopher Marshall
  • 10,678
  • 10
  • 55
  • 94
  • If you think that an answer of another question can answer this question, you should make a comment and point this out (because then the question is a duplicate). Don't copy other answers. At least you gave credit which is good :) – Felix Kling Jan 08 '12 at 22:27
  • 1
    Sorry, I just saw that you already made a comment... you need 3000 rep for voting a question to close. – Felix Kling Jan 08 '12 at 22:32