Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Jquery to colour the background of an element, based on keywords within the html

I'm trying to use Jquery to firstly identify specific words within a span tag, and then colour the background of a div it is nested in. The HTML looks like this:

<div class="highlight item1 ll3">
<div class="Image">
<h2 class="Name">
<div class="type">
<span>Workshop</span>
</div>
   <div class="Dates">
   <p class="Desc">Toddlers are especially welcome to BALTIC on Tuesdays. Join 
    in the fun, as a BALTIC artist leads a practical session using a variety of       
    materials,...
</p>

So I think I need to use Jquery to identify if equals "Workshop" then color the div with class highlight (for e.g. set background to #000). I need to repeat this so that each div.highlight that has a different value is given a different color.

Thanks so much in advance.

Jason

like image 943
Yippyj Avatar asked Nov 08 '11 17:11

Yippyj


People also ask

How do you change the background color of an element in HTML?

To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.

How can set background color in jQuery?

To add the background color, we use css() method. The css() method in JQuery is used to change style property of the selected element. The css() in JQuery can be used in different ways. The css() method can be used to check the present value of the property for the selected element.

What is the $() in jQuery ()?

When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.

How would you use jQuery to give an element a red background color?

JavaScript Code:add("textarea"). css( "background", "red" ); });


1 Answers

Something like this should work:

$(document).ready(function(){
    $("span:contains('Workshop')").parent().css({ "background-color" : "#f8f8f8" });
});
like image 138
James Johnson Avatar answered Nov 14 '22 17:11

James Johnson