Setting the class of a div based on the contents of a link using jQuery
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($(开发者_JS百科".linkText").val().indexOf("House") == 0){$('#targetDiv').addClass('OpenHouse');};
For some reason this does not work. Any help is appreciated!
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');
精彩评论