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

Encountering an npm issue while attempting to execute the command "npx create-expo-app expoApp"

I've been attempting to set up an expo project, but npm is failing to do so. It does create necessary base files like APP.js, but nothing else. Here's the error I encountered: npm ERR! code ENOENT npm ERR! syscall lstat npm ERR! path C:\User ...

JavaScript events for scrolling horizontally and vertically across multiple browsers

Is there a way to capture mousewheel and touchpad events, including on Mac, using JavaScript? Ideally, I want to get deltaX and deltaY values for both horizontal and vertical movements. I came across a website - - that appears to handle touchpad events ho ...

Comparing AngularJS and AppML

As a beginner in AngularJS and AppML, I am curious to understand the strengths and differences between these two frameworks. Despite some similarities I noticed on W3Schools, I'm eager to dive deeper into each one's unique features. ...

What is the best way to use PHP in order to retrieve the element containing the visit ID from the specific row within an HTML table?

I am working on a project that involves populating an HTML table with data from a database. The table includes an approval button for administrators to approve visits and change their status to APPROVED. I am trying to figure out how to select the element ...

The sequence of data and the final event triggered by http.createServer

const server = http.createServer(async (request, response) => { if (request.method === "POST") { var data = ""; request .on("data", async (chunk) => { console.log("1"); data + ...

Establish the following 13 steps to configure the initial server state and retrieve the client state

Currently, I have 13 applications and I am utilizing Zustand as my state manager. Below is a simple layout example: <MainProvider> <div className="min-h-screen flex flex-col"> <Navbar></Navbar> <main className ...

Pressing the Add button will create a brand new Textarea

Is it possible for the "Add" button to create a new textarea in the form? I've been searching all day but haven't found any logic to make the "Add" function that generates a new textarea. h1,h2,h3,h4,h5,p,table {font-family: Calibri;} .content ...

Journeying through JSON: Presenting the value alongside its hierarchical parent

I'm completely new to JSON Path, so I'm not sure how complicated this could be, or if it's even possible. The JSON structure I have consists of multiple groups, each containing a set of fields. Both the groups and the fields have their own ...

Dynamic Sizing of Elements + Adaptive Text Overlay

There were 2 obstacles I encountered when trying to create an image-based drop-down menu : No matter how much effort I put in, I couldn't figure out how to make a flexed element inside a container maintain the same height as the adjacent element. [ ...

Innovatively blending captivating visuals with informative text, our presentation seamlessly

I'm struggling to resolve a basic code issue and thought you might be able to assist me. Please have a look at the provided sample code on this page: <http://jsfiddle.net/UniqueUser/kkaYc/> As you can observe, when selecting images from the me ...

Learn the ins and outs of Ember.js with our comprehensive tutorial and guide. Discover solutions to common issues such as DS

Learning Ember has been a challenging experience for me. The guide I am using seems to be lacking important information that I need. I keep encountering two specific errors: Uncaught Error: Ember.State has been moved into a plugin: https://github.com/e ...

Is there a way to receive notifications on an Android device when the real-time data updates through Firebase Cloud Messaging (FC

I am attempting to implement push notifications in an Android device using Firebase Realtime Database. For example, if an installed app is killed or running in the background, and a user posts a message in a group (resulting in a new child being added in t ...

Error encountered: DOMException - Prevented a frame originating from "domain_name" from accessing a different origin frame

Utilizing the Mautic newsletter for my website has been a great experience. Here is the js code I've been using: /** This section should only be included once per page if manually copying **/ if (typeof MauticSDKLoaded == 'undefined') { ...

How can I assign a class to my Typography component in Material UI?

When using my material-ui component, I wanted to add an ellipsis to my Typography element when it overflows. To achieve this, I defined the following styles: const customStyles = (theme) => ({ root: { textAlign: "left", margin: theme.spacing( ...

Find the nearest iframe relative to a parent element

I am attempting to find the nearest iframe element to a parent element in order to pinpoint the specific iframe that I want to customize using CSS: <div class ="accroche"> <iframe></iframe> <iframe></iframe> &l ...

Why does the API in Next Js get triggered multiple times instead of just once, even when the strict mode is set to false?

React Query Issue I am currently facing an issue with React Query where the API is being triggered multiple times instead of just once when the selectedAmc value changes. I have tried setting strict mode to false in next.config.js, but that didn't so ...

Align section titles to the right of the screen in Zurb Foundation 4

I'm in the process of incorporating sections to develop a navigation system on a basic webpage. However, I require it positioned on the right side of the screen. The default arrangement generated by Foundation with the use of "vertical-tabs" is "tabs ...

Exploring the depths of Mongoose queries with recursive parent references

I'm attempting to replicate the functionality of this MongoDB example using Mongoose, but it seems more complicated in Mongoose. Am I trying to force a square peg into a round hole? This source is taken from http://www.codeproject.com/Articles/521713 ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

Is it possible to display images in PHP when the value matches the specified string?

Is there a faster and more efficient way to display one or multiple images if $value == $string? For instance, let's say I have a cell containing the string 'r o g'. If a user inputs ro, it should output <img src="red.gif"> and <im ...