When it comes to jQuery, there are numerous approaches to achieving this task. This query can be divided into two main parts:
- How do we specifically target the element we want to highlight?
- How do we actually apply the highlight to that element?
1. Selecting the Element
To start, you may opt to select the element based on certain text criteria:
$(".navbar a:contains('Home')")
Alternatively, you could choose to select the element by its position:
$(".navbar a:eq(2)")
The .navbar
narrows down the selected objects to those within elements with the navbar
class. The subsequent part, a
, further refines the selection to only a
elements. For the first method, the :contains()
functions as a content filter. Since it's not the most efficient filter, it's best used in conjunction with other selectors (such as $(".navbar a...
). The second method employs the :eq() filter. While this answer presents these two selector options, refer to my response to the question about selecting nested divs with jQuery for additional examples of similar jQuery selectors.
2. Applying the Highlight
Now that we have identified the desired element, let's proceed with the highlighting process. One direct approach is to manipulate the CSS background-color property directly:
$(".navbar a:contains('Home')").css('background-color', 'orange');
An alternative method that I find preferable involves creating a class with the desired styling (e.g., .highlighted) and utilizing jQuery's addClass()
function:
CSS
.highlighted {
background-color: yellow;
}
JavaScript
$(".navbar a:contains('Home')").addClass('highlighted');
Moving Forward
For a practical demonstration of these techniques, check out this example on jsFiddle.
*I've chosen to utilize jQuery for this solution due to Bootstrap's integration with jQuery.