Tips on modifying li styles using javascript

I have a link that looks like this:

<a href="#" onclick="changeClass()">My Button</a>

with the following CSS style applied:

.tree li a:hover, .tree li a:hover+ul li a {
    background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}

Now, my question is how can I change this .tree style to a different one? And if I click on it again, how do I make the style return to the original?

Answer №1

There are two ways to accomplish this task, one using plain JavaScript and the other using jQuery:

var id = 'myElementId';
var myClassName = " tree";
var d;

function changeClass() {
  d = document.getElementById(id);
  if (d.className == ' tree') {
    d.className = d.className.replace(myClassName, "");
  } else {
    //d=document.getElementById('myElementId');
    d.className = d.className.replace(myClassName, ""); 
    d.className = d.className + myClassName; 
  }
}
.tree {
  background: #c8e4f8;
  color: #000;
  border: 1px solid #94a0b4;
}
<a id="myElementId" href="#" onclick="changeClass()">My Button</a>

Alternatively, you can achieve the same result with jQuery by toggling the class:

var id = 'myElementId';
var myClassName = " tree";

function changeClass() {
  $('#' + id).toggleClass(myClassName);
}
.tree {
  background: #c8e4f8;
  color: #000;
  border: 1px solid #94a0b4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="myElementId" href="#" onclick="changeClass()">My Button</a>

Answer №2

To switch between classes, you can utilize the classList.toggle("className") method.

var box = document.getElementById("myBox");
box.classList.toggle("activeClass");

Answer №3

Below is a concise javascript function for toggling class names:

function toggleClassNames(element, className1, className2) {
  if(new RegExp("\\b"+className1+"\\b").test(element.className)) {
    element.className = element.className.replace(new RegExp("\\b"+className1+"\\b",'g'),className2);
  } else {
    element.className = element.className.replace(new RegExp("\\b"+className2+"\\b",'g'),className1);
  }
}
a {
  display:block;
  padding:10px;
  color:white;
}
.myclass1 {
  background:red;
}
.myclass2 {
  background: green;
}
<a href="#" class="myclass1" onclick="toggleClassNames(this,'myclass1','myclass2')">My Button</a>

Note: Ensure that the class name is not part of another word.

Answer №4

An effective method for achieving this is by creating a new CSS class selector and defining your preferred styles within it in the CSS file, such as .my-tree.

.my-tree {
    color: red;
}

When the anchor is clicked, you can then apply this CSS class to your tree element.

var treeEl = document.getElementById("tree"); 

treeEl.className = treeEl.className + " my-tree";

Likewise, you are able to remove this CSS class using a flag variable in your code to toggle its presence.

One convenient approach is utilizing the toggleClass method provided by jQuery for a seamless addition or removal of the specified CSS class.

Answer №5

If you're looking for a pure CSS solution, here's an alternative approach:

[type=checkbox] {
  display:none;
}

/* Styling the div following the checkbox */
[type=checkbox] + div {
  background:purple;
  cursor:pointer;
}

/* Styling when the checkbox is checked */
[type=checkbox]:checked + div {
  background:green;
  color:#fff;
}
<label>
  <input type="checkbox">
  <div>Click me!</div>
</label>

While this may not conform to traditional HTML standards, it offers a straightforward way to toggle elements if validation isn't a concern. For a more compliant option:

[type=checkbox] {
  display:none;
}

[type=checkbox]:checked + label {
  background:green;
  color:#fff;
}

[type=checkbox] + label {
  background:purple;
  display:block;
}
<input id="toggle-button" type="checkbox">
<label for="toggle-button">
  Click me!
</label>

Just something different to consider.

Answer №6

Check out the jQuery documentation

This is how you can achieve it:

<a href="#" id="myLink">Click Me</a>

JavaScript:

   $( "#myLink" ).click(function() {
     $( "#myLink" ).toggleClass("first");
     $( "#myLink" ).toggleClass("second");
  });

CSS:

.first {
    background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}

.second {
    background: #000; color: #fff; border: 1px solid #94a0b4;
}

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

What's the best way to retrieve information from Mongodb in order to generate a map marker?

I have a map where I need to place markers. I've created a collection in MongoDB and have a sample data set ready for the marker. However, I am having trouble retrieving the data and actually creating the marker on the map. The Map Meteor.star ...

Javascript experiencing issues with Heapsort

I have been working on implementing heapsort in JavaScript, but I've encountered an issue with an undefined element at position array.length - 2, and the element at index 0 is not sorted. Here is the code snippet: var heapSort = function(array) { ...

"Oops! Looks like there is an issue with the configuration of the builder. Try running `npm run storybook

Encountering an error when attempting to execute npm run storybook following what seems like a smooth installation of Alpha 7. Any suggestions on where to begin troubleshooting this issue? https://i.sstatic.net/EEFx4.png ...

What is the best way to execute a script on the homepage just one time?

I need some assistance with a script that should only run when a visitor arrives at my site for the first time. I want all content to be hidden initially and then revealed in a visually appealing way when the visitor clicks a button. However, I do not want ...

The search results in ajax live search are present, but unfortunately they are not displaying on

I am currently working on a code for an ajax live search feature and need some help with getting results to display $(document).ready(function() { $("#search").keyup(function() { var query = $(this).val(); if (query != "" && query.leng ...

Is it possible to target all children with CSS3 if a certain number of children are present?

I've been racking my brain trying to select all children if there are x or more children present. I want to be able to select all child elements if there are at least x children. So far, I've managed to target all children when there are exactl ...

Creating a website with a responsive layout using CSS absolute positioning

Is there a way to make this css code responsive for a website? I believe I need to use: @media (min-width: 700px) and (max-width: 1150px) { #div {position: absolute; left: 149px; top: 61px;} #div2 {position: absolute; left: 249px; top: 81px;} ...

Responsive left and right image styling in CSS and HTML

I have designed a landing page with fixed left and right images and content in the middle. It looks fine on desktop view, but on mobile view, the images are overlapping the content. How can I resolve this issue? <div class=" ...

What is the best way to halt a JavaScript function originating from embedded iframe content?

When I embed another website using iframe, there is a javascript function on their page that I do not want to run on my own page. Here it is: if (top.location != location) { top.location.href = document.location.href; } I attempted a solution but it ende ...

Angular UI directive for modal confirmation

Looking to create a custom Angular directive using angular-bootstrap that mimics the confirm() function. Check out the visual result and desired behavior in this plunk: http://embed.plnkr.co/27fBNbHmxx144ptrCuXV/preview Now, I want to implement a directi ...

What is the recommended way to configure the build.gradle file for the app build process?

I am currently working on building the app using the command provided below. /android gradlew assembleRelease My main query at this point is whether it is necessary to eliminate the debug of signingConfigs and debug of buildTypes when transitioning into r ...

Split into two lines, the Bootstrap carousel includes 28 indicators for easy navigation

I am currently using a Bootstrap 4 carousel with 28 pictures. However, I am facing an issue where the indicators on small and medium devices are not displaying properly (some indicators seem to be missing). They are not breaking into new lines as expected. ...

We have successfully integrated the Wijemo event calendar with our Angular controller

I've been attempting to connect the wijeval to an array of events within an AngularJS Controller. Here's what I've attempted so far: View: <div ng-app="MyApp" ng-controller="MainController"> <wijevcal viewtype="week" eventsdat ...

Can a person select a characteristic like "height" using Javascript?

Is it doable to set a height for an image in CSS, then detect this gradient using JS and double the width based on the height x2.25? Could this be achieved? ...

Initialize an array containing five zero elements

How can I initialize an array with 5 zero elements in JavaScript without using the classic var arr = [0, 0, 0, 0, 0] method? I've tried a few variations: var arr = new Array(5).map(() => 0); var arr = new Array(5).map(function () {return 0;}); va ...

When using Express.static, the website functions properly but an error message "GET http://localhost:5000/index.js net::ERR_ABORTED 404 (Not Found)" is displayed

Having an issue with express.static. My project is a basic portfolio website that includes a form for sending emails. I referred to this tutorial on Nodemailer: Tutorial Nodemailer Github The problem arises within my index.html file (this example applies ...

Adding a margin space to the right of the header using Bootstrap

As I embark on creating my very first Bootstrap website, I have encountered what seems like a simple issue that is causing me quite the headache. There appears to be an unexplained 20px margin on the right-hand side of the page, persisting across all brows ...

"Express API POST request functions successfully on Postman, however encounters difficulties when used with AJAX

My goal is to send an AJAX request from JavaScript to my ExpressJS Rest API. Unfortunately, the POST call is not working in JavaScript. Interestingly, when I use Postman, the same JSON data with the same headers works perfectly. Here is the error I&apos ...

Scaling CSS images to fit within a specific area without distorting them

Is there a way to ensure that an image fits within a specified area using CSS or other methods? For example, if I have images of various sizes and want them all to fit into a div of 150px by 100px without stretching or distorting them. I just want the imag ...

Develop a feature that is designed to reset the password in the user database, only to encounter a failure in the

Currently, I am working on a basic reset function. One of the files on the homepage is a simple html form structured as follows: <html> <body> <div> <form id="reset" action="login/reset.php" method="post"> <fieldset& ...