Implementing CSS class on HTML tags with JavaScript in WordPress

Currently, I am customizing a WordPress theme and I am looking to include an additional class to an element without removing any existing classes. In this particular theme, there is a designated spot for adding JavaScript code within the theme options. By adding my new class to this button, it will toggle to a form. Below is the snippet of code where I intend to insert my new class:

<a href="" target="_self" class="mk-button custom button-5509e751af089 dark-color flat-dimension large pointed"><span>ّFORM</span></a>

Answer №1

WordPress comes with jQuery included by default, making it easy to use:

$('.button-5509e751af089').toggleClass('myClass');

If you prefer using vanilla JavaScript, you can achieve the same result like so:

document.getElementsByClassName('button-5509e751af089')[0].classList.toggle('myClass');


This will only toggle the class of the first element, unlike the jQuery approach.

For more details on classList, refer to this link.


To dynamically set the class based on an input value, replace 'myClass' with the following code in your script:
jQuery:

$('input.myInput').val();

JavaScript:

document.getElementsByClassName('inputClassHere')[0].value


Note: You can also use .querySelector(".myClass") instead of
.getElementsByClassName('myClass')[0]

Answer №2

Deciding whether to apply this class to all buttons on the page or just one will determine your approach. If you want to target all buttons, you can achieve that by following these steps:

var elements = document.querySelectorAll(".mk-button");

for(var i = 0; i < elements.length; ++i) {
    var el = elements[i]
    el.className = el.className + " new-class-here";
}

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

Unable to append an extra element to the (mongoose) entity

In my nodejs express app, I have an API that retrieves data from a MongoDB database. Here is the mongoose model I am using: const bookingSchema = new mongoose.Schema({ timestamp: { type: Date, default: Date.now, required: true }, tags: { ...

I want to adjust the size of a <div> element as an image is being resized using Bootstrap's "img-responsive" class

When adjusting the browser size, the images are resized which is great because it's exactly what I intended. However, the lower part of the black area does not resize accordingly. This results in a black area appearing under the images when viewed on ...

The event binding for input with the specific class `.SomeClass` in the document is functional in Chrome, but encounters issues in Internet Explorer

I am facing an issue where I have a span with the contenteditable attribute and a function to detect input within it. //TextArea <span class="SomeClass" contenteditable></span> //Function $(document).on("input", ".SomeClass", function () { ...

The functionality of Google Map APIs is not compatible with Angular views

I'm currently attempting to utilize Google Maps APIs to create a basic autocomplete feature for a "Place" input box within an Angular routing setup. Following Google's developer instructions, in the <head> of my main template, I've in ...

Parameters in functions are received by value

When working with JavaScript, one common point of confusion is the way variables are treated based on their data type. Variables of primitives are passed by value, while variables of objects are passed by reference. However, in function arguments, both pri ...

Setting up a route for a WebSocket server in Express: a step-by-step guide

My setup is structured similarly to the following code: const WebSocketServer = require("ws").Server, express = require("express"), http = require("http"), app = express(), server = http.createServer(app); app.post("/login", login); app.g ...

What could be the reason for rowsAffected not returning an integer value?

Currently, I am working on executing the SQLite statement in an iOS application. To verify the count of affected records, I have implemented success and error callback methods. Upon receiving the results, although the variables are correctly defined, I en ...

Selecting the content within a table to easily edit it

I am working on a project where I have a table filled with data fetched from a database. My goal is to allow users to click on a cell in the table, make changes to its content, and then save those changes back to the database. Below is the code snippet I a ...

Getting the value of an anchor tag in Laravel and utilizing it within an input field

I am facing an issue where $emp->id provides the correct id, but when I try to get id={{$emp->id}} it doesn't work as expected. Can someone please help me with this problem? <a href="{{'/employee'}}?id={{$emp->id}}" type="button ...

Combining queries in mongodb with nested joins

I'm attempting to retrieve a structure where I first populate content, and within content there is an array field named comments. From comments, I aim to populate user. Below is the schema: const contentScheme = new Schema({ post_id: { type: Num ...

What is the reason behind material-ui's decision to invoke their dialogs twice?

After attempting to implement a modal and realizing the strange behavior, I switched to using a dialog instead. To my surprise, the issue persisted. This is how I approached it: import Dialog, { DialogProps } from '@material-ui/core/Dialog'; imp ...

What is the parent selector in cascading style sheets (CSS

Is there a way to use pure CSS to identify the parent selector of a child element? #checkbox{ width: 24px; height: 24px; vertical-align: middle; } #checkbox:checked (parentName){ color: red; } <label for="checkbox"> <input type="check ...

"NaN is being caused by the presence of quotation marks within the split property

Apologies if this question has already been addressed, but I'm struggling to find the answer. I've recently delved into coding as a new hobby and found it quite enjoyable. After using a website that claimed I had learned all there is to know abou ...

Place a "sticky" button directly below a second "sticky" navigation bar

Within my app file, I have customized components like an appbar and various page elements: const styles = theme => ({ appBar: { width:'100%', }, }); class App extends Component { render() { const {classes} = this.props; ...

Using Regular Expressions to Verify Numerous Postal Codes within an Array

I'm currently working on a function that validates postcodes using a regex. The function should be able to handle either a single postcode or multiple postcodes. When I input a single postcode, everything works as expected. However, when I try to inp ...

Bug in floating elements within a header causing issues with IE6 and IE7

We are currently facing an issue where an anchor tag is floating right inside a header. While it displays correctly on IE8 and Firefox, we are encountering problems with it popping outside the header box. Does anyone have any suggestions on how to prevent ...

Timeout Issue with Ajax Datatable

I have been encountering slow response times with my data table due to the large amount of data it contains. Despite using pagination, I still need to retrieve all the data in order to calculate the total value. I attempted setting a timeout, but that did ...

Utilize Ajax to add a query into a PHP script

I am facing an issue with a AJAX call as I keep receiving error 500. However, it is unclear to me whether the problem lies in the AJAX call or the PHP file. Below are my JavaScript and PHP code snippets: $.ajax( { type: "POST", url: &ap ...

A different method to generate a random number between 0 and 9 in Angular 8

Looking for an alternative to Math.floor(Math.random()*10) in Angular 8? I need to remove math.random() due to security concerns. A suggestion was made to use PRNG, but I'm not familiar with how to do that. Any assistance would be greatly appreciated! ...

I am facing a challenge in retrieving a response from the jQuery AJAX Success function

Hey everyone, I'm currently working on an application that requires me to obtain the server time before sending out AJAX requests. The challenge lies in accessing the server time by making a request through AJAX. Here's the code snippet within my ...