Is it possible to change the CSS styling of a specific DIV class that contains nested anchor tags using jQuery?

The HTML:

<div id="main_menu">
    <a id="menu_item_articles" href="articles">articles</a>
</div>

The CSS:

#main_menu {
    float: left;
    padding-top: 10px;
    vertical-align: middle;
    text-align: center;
    width: 500px;
}

#main_menu a {
    border: 1px solid #000;
    font-weight: bold;
    background: #fff;
    color: #000;
    padding: 7px;
    text-decoration: none;
}

#main_menu a:hover {
    border: 1px solid #000;
    font-weight: bold;
    background: #ff9935;
    color: #000;
    padding: 7px;
 text-decoration: none;
}

.selected_menu_item {
    background: #ff9935;
    color: #000;
}

My Goal with jQuery:

Edit: Included the missing piece of code (pathArray), which extracts the path depending on whether it's a development environment or not.

var pathArray = $(location).attr('pathname').split('/');
var selectedMenuItem = (pathArray[1] == 'sitename') ? pathArray[2] : pathArray[1];
$('#menu_item_' + selectedMenuItem).attr('class', 'selected_menu_item');

Essentially, I aim to retrieve the current page's URI, break it down, extract the page name, and then highlight the corresponding menu item once the page has finished loading ($(document).ready()).

It appears that the "#main_menu a" styling defined in my CSS is rigid and not allowing the new style to be applied. Any recommendations?

Answer №1

Your jQuery code seems to be in order. It's worth noting that you may want to provide more specificity to your CSS .selected_menu_item class selector:

#main_menu a.selected_menu_item {
    background: #ff9935;
    color: #000;
}

If not, the background color may be overridden by the styles applied to #main_menu a due to the higher specificity of the ID selector on your <div> compared to a class selector alone. This could give the impression that your class styles are not taking effect.

Answer №2

Take a look at this illustration. I am working on a similar project here:

Hopefully this will give you a good starting point.

John

Answer №3

My recommendation would be to handle this logic in the server-side code. By doing so, you can avoid relying on JavaScript to perform the task, especially if you are already loading a different page. This approach can also enhance the functionality of the page in situations where JavaScript is disabled.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having some trouble getting Backstretch to function properly. It keeps giving me a 404 error when I attempt to load it

In my free time, I am working on a small webpage using python/django with bootstrap. Frontend development is not my strong suit, so I try to keep things simple. Recently, I came across the backstretch plugin and thought it would be easy to set up and add a ...

Conceal the initial modal beneath the overlay when the second modal is activated

I have a situation where I am using a modal that contains a button to trigger a second modal. The issue is that the overlay of the second modal does not hide the first modal, it simply darkens the background. How can I make the overlay of the second modal ...

Velocity 1.5 causing issues with jQuery compatibility

I am encountering issues with incorporating jQuery into my code within a velocity template. Despite using velocity 1.5, the jQuery functionality does not seem to be working properly. Could you please suggest a solution? <script src="/CostTrackerReport ...

What steps do I need to follow to change the background color to white for the <App/> component in solid-js?

In my solid-js application styled with tailwindcss, I established a gray color in the index.css for the background of various screens. However, I wanted the main <App/> component to have a white background instead. To achieve this, I created an App.c ...

Utilizing Ajax: Sending Customized Data to a Modal

Having never worked with jquery before, I struggled to find a solution for my specific case. On the cockpit.php page, I have a form that retrieves content from a mysql database. Currently, I am able to display this content in a div on the same cockpit.php ...

There has been an issue with parsing the JSON file due to an invalid character found at

I keep encountering a parse error whenever I attempt to send a post request to the server. $.post("../php/user_handler.php", formData, function(data) { var result = JSON.parse(data); if(result.status === 'error') { ...

What could be causing my object to not be added properly to a select element using JavaScript programmatically?

When it comes to customizing your pizza, the options are endless. From selecting the type of crust to choosing your favorite toppings, every detail matters. One common issue that arises is when changing the crust type affects the available sizes ...

Sending date and time data to a controller action using jQuery AJAX

How can I send a datetime value to a controller action using jQuery Ajax, while utilizing jQuery UI datepicker for textboxes and calendar controls? The current action is still set as controller/action/11/12/2011 which seems to not be functioning correctly ...

Using JavaScript and jQuery, apply a class when a specific radio button is checked and the data attribute meets certain criteria

Need help with changing explanation color based on correct answer selection in multiple choice question. Currently, all choices turn green instead of just the selected correct one. Any assistance is welcome, thank you. html <li class='test-questi ...

What Makes Sports Illustrated's Gallery Pages Load So Quickly?

After thoroughly examining their code, I'm still puzzled. Are they loading complete new pages, or are they utilizing jQuery to modify the browser's URL while keeping most of the page unchanged? I'm currently inspecting the source of this pa ...

Place two anchors side by side using inline-blocks without using the float property

Is there a way to align two buttons next to each other without using floating? I have encountered an issue where adding a width to one of the buttons causes it to jump down and be on a different line than the other button. The buttons are centered, so th ...

Steps for creating a table with a filter similar to the one shown in the image below

https://i.sstatic.net/zR2UU.png I am unsure how to create two sub-blocks within the Business A Chaud column and Potential Business Column. Thank you! I managed to create a table with input, but I'm struggling to replicate the PUSH & CtoC Column for ...

Ways to create a self-contained video viewer

Is it possible to create a self-contained video player similar to jwplayer or the YouTube video player using just HTML, CSS, and JavaScript? I know that I can build a video player by utilizing the video tag along with some custom javascript and css, but ho ...

Unable to invoke the jQuery datetimepicker function within a personalized directive

I have created a unique time picker directive in AngularJS to display a datetimepicker. app.directive("timePicker", function() { return { restrict: "A", link: function(scope, elem, attrs) { / ...

What could be causing textbox2's value to not update when textbox1's value is changed? (Novice)

I am looking to create an interactive form with two textboxes and a checkbox. When the checkbox is checked, I want the value of textbox2 to mirror whatever is typed into textbox1. Is there a way to have the value of textbox2 automatically updated when the ...

Instead of using onload, activate function upon click instead

Upon page load, I have a function that executes: function loadData(page){ showLoading(); $.ajax({ type: "GET", url: "load_data.php", data: "page="+page, success: function(msg) { ...

What are the steps to modify the "text" displayed on a button in a kendo grid?

How can I change the default button text "add new record" on my kendo grid? I attempted to modify it using the following code, but it did not work: #turbinegrid .k-icon.k-add::after { content: "ADD"; } ...

The behavior of the jQuery click function seems to be quirky and not functioning as expected. Additionally, the

It seems that instead of triggering a POST request, somehow a GET request is being triggered. Additionally, the ajax call is not being made as expected. I have attempted this many times before, but none of my attempts seem to be working. It could potenti ...

Enhancing gallery user experience with jquery to animate the opacity of active (hovered) thumbnails

I am attempting to create an animation that changes the opacity of thumbnails. By default, all thumbnails have an opacity of 0.8. When hovered over, the opacity should increase to 1 and then return to 0.8 when another thumbnail is hovered over. Here is th ...

Tips for resizing the width automatically within a container?

I am facing an issue with a container that contains 3 DIVS: left sidebar, main content, and a right sidebar. I have made the main content responsive by setting the width to width:calc(100% - 400px); (where 400px is the combined width of the sidebars). Howe ...