tags:

views:

19

answers:

1

This is probably pretty simple but I can't figure it out! I need to parse the text inside an tag and set the class of a div based on it's contents. Here's what I need to do:

<div id="targetDiv">  Content Here  </div>
<a href="/BookingRetrieve.aspx?ID=6463">Open House - October 21, 2010</a>
<a href="/BookingRetrieve.aspx?ID=6463">Meeting - October 21, 2010</a>

I need to set the class of the first div to either "OpenHouse" or "Meeting" based on the contents of the text string inside the tag. (Note: only one would be showing. I'm including both only for reference).

So if this were showing on the page:

<a class="linkText" href="/BookingRetrieve.aspx?ID=6463">Open House - October 21, 2010</a>

The div would be

<div id="targetDiv" class="OpenHouse">  Content Here  </div>

Here's the jQuery:

if($(".linkText").val().indexOf("House") == 0){$('#targetDiv').addClass('OpenHouse');};

For some reason this does not work. Any help is appreciated!

+3  A: 

Instead of .val() you need .text(), like this:

if($(".linkText").text().indexOf("House") == 0){$('#targetDiv').addClass('OpenHouse');}

but that's a starts-with check, if you want a contains do >= 0 like this:

if($(".linkText").text().indexOf("House") >= 0){$('#targetDiv').addClass('OpenHouse');}

Or just use :contains(), like this:

if($(".linkText:contains('House')").length){$('#targetDiv').addClass('OpenHouse');}

Or if like your example the <div> is just before the <a>, you can do this:

$(".linkText:contains('House')").prev().addClass('OpenHouse');
$(".linkText:contains('Meeting')").prev().addClass('Meeting');
Nick Craver
In your last example, I think you want `.length > 0`. ;-)
Ben Blank
@Ben - In javascript `>0` ~= `true`, it works without it :)
Nick Craver
I knew I was close! This works perfectly! Thanks.
mmsa
@Nick — When I wrote that comment, it still said `.length >= 0`, which *isn't* quite the same. :-)
Ben Blank
@Ben - It *was* `> 0` for a moment, you would never use `>= 0` for `.length`, not in any case I can think of anyway...
Nick Craver
@Nick — Precisely my point. It looked like it had been copy/pasted from the second example and I didn't know you were still editing the answer, so didn't want it to slip by.
Ben Blank