Utilize JavaScript to append a CSS class to a dynamic unordered list item anchor element

I am working with a list of ul li in a div where I need to dynamically add CSS classes based on the click event of an anchor tag.

Below is the HTML structure of the ul li elements:

<div class="tabs1">
    <ul>
       <li class="active"><a href="javascript:;" onclick="change_program()" class="program active" title="Program"></a></li>
       <li><a href="javascript:;" onclick="change_sd()" class="sd" title="Discriminative Stimulus"></a></li>
       <li><a href="javascript:;" onclick="change_response()" class="response" title="Response"></a></li>
       <li><a href="javascript:;" onclick="change_enforces()" class="enforces" title="Reinforcers"></a></li>
       <li><a href="javascript:;" onclick="change_sro()" class="sro" title="Short Range Objective"></a></li>
       <li><a href="javascript:;" onclick="change_lro()" class="lro" title="Long Range Objective"></a></li>
       <li><a href="javascript:;" onclick="change_prompt()" class="prompt" title="Prompt"></a></li>
     </ul>
  </div>

The above anchors trigger specific JavaScript functions, changing the display style of different elements. Here are the functions:

function change_program(){ 
    // code to change display styles
}
// Other similar functions for different tabs

I aim to achieve this dynamic behavior by manipulating classes through JavaScript without reloading the page.

Each anchor tag's corresponding CSS properties are defined as follows:

<style>
.tabs1 ul li a.program:active {
  width: 129px;
  background: url(../images/program_steps_h.png) no-repeat;
}
// Styles for other anchor tags
</style>

Answer ā„–1

Maybe you are looking for this:

$(function () { // when the page is loaded
    // when a link in the UL is clicked
    $("div.tabs1>ul>li>a").on("click", function (e) {
        e.preventDefault(); // prevent default click behavior
        $(this).closest("ul").find(".active").removeClass("active"); // remove active class from all elements under the UL
        $(this).addClass("active"); // add active class to the clicked element
        $(this).parent().addClass("active"); // add active class to the parent LI of the clicked element
        $(".toggleDiv").hide(); // hide all target divs with the toggleDiv class
        $("#"+$(this).data("target")).show(); // show the target div based on data-target attribute of the clicked link
    }).first().click(); // simulate click on the first link when page loads
});

using

<div class="tabs1">
    <ul>
        <li><a href="#" data-target="program" class="program" title="Program">Program</a></li>
        <li><a href="#" data-target="sd" class="sd" title="Discriminative Stimulus">SD</a></li>
        <li><a href="#" data-target="response" class="response" title="Response">Response</a></li>
        <li><a href="#" data-target="enforces" class="enforces" title="Reinforcers">Enforces</a></li>
        <li><a href="#" data-target="sro" class="sro" title="Short Range Objective">SRO</a></li>
        <li><a href="#" data-target="lro" class="lro" title="Long Range Objective">LRO</a></li>
        <li><a href="#" data-target="prompt" class="prompt" title="Prompt">PROMPT</a></li>
    </ul>
</div>

<div id="sro" class="toggleDiv">SRO....</div>
<div id="sd" class="toggleDiv">SD...</div>

$(function () {
    $("div.tabs1>ul>li>a").on("click", function (e) {
        e.preventDefault(); // cancel click
        $(this).closest("ul").find(".active").removeClass("active");
        $(this).addClass("active");
        $(this).parent().addClass("active");
        $(".toggleDiv").hide();
        $("#"+$(this).data("target")).show();
    }).first().click(); // click the first on load
});
.toggleDiv { display:none }
li.active { background-color:red } 
.active { color:yellow }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="tabs1">
    <ul>
        <li><a href="#" data-target="program" class="program" title="Program">Program</a></li>
        <li><a href="#" data-target="sd" class="sd" title="Discriminative Stimulus">SD</a></li>
        <li><a href="#" data-target="response" class="response" title="Response">Response</a></li>
        <li><a href="#" data-target="enforces" class="enforces" title="Reinforcers">Enforces</a></li>
        <li><a href="#" data-target="sro" class="sro" title="Short Range Objective">SRO</a></li>
        <li><a href="#" data-target="lro" class="lro" title="Long Range Objective">LRO</a></li>
        <li><a href="#" data-target="prompt" class="prompt" title="Prompt">PROMPT</a></li>
    </ul>
</div>

<div id="sro" class="toggleDiv">SRO....</div>
<div id="sd" class="toggleDiv">SD...</div>

Answer ā„–2

Elements cannot have pseudo-classes added to them, only real classes are applicable. Pseudo-classes serve to indicate changes in the browser's state, such as :hover when the mouse hovers over an element.

Instead of using selectors like .tabs1 ul li a.prompt:active, opt for .tabs1 ul li a.prompt.active. Subsequently, you can utilize jQuery:

$(selector).addClass("active");

This will effectively add the specified class to certain elements on the page.

Answer ā„–3

If you're interested, here's an example of what you might be searching for:

<p id = "click-me">Hey there!</p>

<script type="text/javascript">
    document.getElementById("click-me").className = "hello-friend";
</script>

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

Dynamic image swapping using JSON key in Angular

Trying to display different icons based on a property that contains specific words. If the property includes "Health Care" or "Health Care .....", I want to show one image, otherwise another. I've tried using ng-show but my syntax seems off. Any sugge ...

Interact with jQuery to trigger events upon clicking on a list item, excluding checkboxes within the list

I'm in the process of developing a straightforward web application. I have a dynamically generated list on one section: Subsequently, I set up an event that triggers when any element within the list is clicked: $(document).on('click', &apo ...

Determining the location of the hamburger item on the bar

As I work on creating a hamburger icon, I am faced with the challenge of accurately positioning the bars without guessing. The height of the hamburger is 24px, and I initially thought placing the middle bar at half the height (12px or top: 12px) would cent ...

Using JavaScript to dynamically retrieve element IDs

Within the content on my page, there are multiple tables displaying product information along with their respective authors. Additionally, there is a div that contains hyperlinks for each author. Currently, I am linking the authors' names to hyperlink ...

SignalR 2.2 users are experiencing a lack of message reception

I have developed a unique self-hosted SignalR application that is operating within the framework of a console application. To access the hubs within this application, I have implemented a wrapper class to avoid referencing the SignalR.Core assemblies direc ...

Intermittent occurrence of (404) Not Found error in the SpreadsheetsService.Query function

Using the Spreadsheet API, I frequently update various sheets. Occasionally, and without any pattern, the SpreadsheetsService.Query function returns a (404) Not Found error. This issue does not seem to be related to internet connectivity or server downti ...

Encountered an issue during the installation of react router - in need of assistance to resolve the error

Encountering an Error Error Message when Installing React Router DOM: npm WARN: The use of global `--global` and `--local` is deprecated. Use `--location=global` instead. npm ERR! code EPERM npm ERR! syscall mkdir npm ERR! path D:\ npm ERR! errno -404 ...

What is the most effective method for combining data from two APIs into a single React table?

Looking to combine data from 2 separate APIs that both have pagination capabilities. What is the most efficient method to present the merged data in a table? The data needs to be joined based on their unique id, however one API provides fewer records tha ...

Identifying copy and paste behavior within an HTML form using .NET CORE MVC 2.1

I inherited a project at my current company and one of the tasks involves allowing users to paste multiple ISBN numbers from Excel into a search field on my Index page (HTML). Sometimes, the ISBNs are poorly formatted with letters or special symbols mixed ...

Using JavaScript to block form submission based on AJAX response

I am having trouble understanding why this code is not working as expected to prevent a submit. I have made sure all the HTML elements are properly linked and all alerts display correctly. It doesn't seem like I am losing scope on the event. If anyone ...

Inquiry regarding jQuery duplication

Seeking assistance with jQuery Here is the code snippet I am currently using: $( '#wall_msg').clone( true ).insertAfter( '#wall_msg' ); I need help figuring out how to set a unique ID for the cloned element and also fade it in using ...

What is the functioning process of the angular method decorator?

The tutorial on creating custom decorators in Angular introduces a throttle decorator that utilizes the lodash throttle function. The implementation of this decorator can be seen below: import t from 'lodash.throttle'; export function throttle( ...

Executing an external Python script within a Vue application's terminal locally

Hello, I am new to using Vue.js and Firebase. Currently, I am working on creating a user interface for a network intrusion detection system with Vue.js. I have developed a Python script that allows me to send the terminal output to Firebase. Right now, I a ...

set up the router by defining the behavior for each route

My goal is to redirect the user back to the homepage when they click the browser's back arrow to return to the previous page. However, I'm facing an issue where I cannot go back to the previous page when I'm on the login page using the brow ...

Issue with HTML input tag in MVC 4 causing error message "string constant not properly terminated"

Hello, I am encountering an error while attempting to create a button in HTML. The error message states: "Unterminated string constant" Below is the code snippet causing the issue: <input id="topImageNavigationPreviousButton" type="button" value="Previ ...

Switch the header from left to right movement for mobile devices

I am dealing with two headers in my layout <section> <header class="col-lg-9"> <!-- some content --> </header> <header class="col-lg-3"> <!-- some content --> </header> </section ...

In the Rails environment, it is important to verify that the data sent through $.post method in jQuery is correctly

Iā€™m facing an issue with my jQuery script when trying to post data as shown below: $.post({ $('div#location_select').data('cities-path'), { location_string: $('input#city_name').val() }, }); Although this code work ...

What is the correct way to write the syntax for wp_register_style function in

I'm attempting to include a cache-buster version in my CSS file. The guides mention: <?php wp_register_style( $handle, $src, $deps, $ver, $media ); ?> However, I've scoured Google and Stack Overflow for the correct formatting of these var ...

How can I trigger an Onclick event from an <a tag without text in a Javascript form using Selenium?

Here is my original source code: <a onclick="pd(event);" tabindex="0" issprite="true" data-ctl="Icon" style="overflow: hidden; background: transparent url("webwb/pygridicons_12892877635.png!!.png") no-repeat scroll 0px top; width: 16px; height: 16px ...

accessing the php script within a node environment

Hey there! I'm currently working on creating a chat system using socket.io, express.io, and node.js. So far, everything has been going smoothly as I've been following the documentation provided by these tools. However, when I attempt to integrat ...