As in most things with jQuery*, there are many different ways to accomplish this. This question can be broken down into two parts:
- how do we select only the element that we want to highlight?
- List item how do we apply a highlight to the element?
1. Select the element
For the first part, you may want to select the element that has a certain text:
$(".navbar a:contains('Home')")
Or you may prefer to select the element by position:
$(".navbar a:eq(2)")
Let's break this selector down. The .navbar
limits the returned objects to only the things within element(s) having the navbar
class. The second part, a
, further filters those objects to only the a
elements. For the first option, :contains()
is a content filter. It's not one of the fastest filters, so you'll want to use it in conjunction with other selectors (in this case $(".navbar a...
). The second option uses the :eq()
filter. Though I'm only proposing these two selector options in this answer, see my answer to jquery select nested div for examples of other similar jQuery selectors.
2. Apply the highlight
Now that we have the element we want, let's apply the highlight. The most straightforward way to do so would be to just brute-force the css background-color property:
$(".navbar a:contains('Home')").css('background-color', 'orange');
An alternative that I prefer is to create a class with the intended styling (.highlighted
for this example), and apply it using jQuery's addClass()
method:
CSS
.highlighted {
background-color: yellow;
}
JavaScript
$(".navbar a:contains('Home')").addClass('highlighted');
Go forth
See http://jsfiddle.net/jhfrench/eMk7N/ for a working example of these concepts.
*-I'm using jQuery to solve this because Bootstrap is built with jQuery.