Add css Class on html element using JavaScript in WordPress - javascript

I'm working on a theme in WordPress I want to add a new class to an element without removing existing class in this theme there is a place
to add javascript code in theme option with my new class this button
will toggle to a form here is the code that I want to add my new
class into it.
<span>ّFORM</span>

jQuery is included by default in WordPress, this can be done by:
$('.button-5509e751af089').toggleClass('myClass');
With regular JavaScript, I would do the following:
document.getElementsByClassName('button-5509e751af089')[0].classList.toggle('myClass');
These method will only toggle the class of the first item, unlike the jQuery answer.
More information on classList here
If you would like the value of the class to be from an input, replace 'myClass' with the following
jQuery:
$('input.myInput').val();
JavaScript:
document.getElementsByClassName('inputClassHere')[0].value
EDIT: One can also use .querySelector(".myClass") instead of .getElementsByClassName('myClass')[0]

it depends on if you want to add this class to all buttons on the page or just one. assuming you want all buttons, you would do the following:
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";
}

Related

Unable to change the class of a div using JavaScript

So I got into JavaScript and tried setting up the following scenario:
I have 2 Buttons on my Site (IDs are buttonWebdev and buttonUXUI), which should trigger an Action when they are hovered upon. If buttonWebdev is hovered upon, it should hide all p', h3's and imgs with the class "classWeb". I wrote this code to do it, but it doesn't work:
HTML:
<h3 class="classWeb">Editierbare Inhalte</h3>
<p class="classWeb">Test</p>
<button class="buttonImg" id="buttonWebdev"><img src="./img/buttonWebdev.png" /></button>
<script type="text/javascript">
var button = document.getElementById('buttonWebdev');
var classWeb = document.getElementsByClassName('classWeb');
button.onmouseover = function() {
classWeb.className = 'webdev';
}
CSS:
.classWeb.webdev {
display: none;
}
First, since there can be more than one element with a given class on a page, getElementsByClassName returns a list of elements instead of a single element. You’ll need to perform your action on every element of that list, with a for…of loop, for example:
for (let element of classWeb) {
element.className = 'webdev';
}
(for…of is relatively new, though, so you might have to use a regular for loop depending on your target browsers.)
After fixing this, you’ll run into another problem. When you assign to className like that, you’re setting the entire list of classes on an object. If the list of classes is 'webdev', it no longer includes 'classWeb'. Modern browsers support an API to add a class without affecting the rest:
for (let element of classWeb) {
element.classList.add('webdev');
}
The way to diagnose these sorts of problems is by opening up your browser’s developer tools, looking for JavaScript errors in the console, and looking at the state of the elements you’re trying to affect in the document tree.
document.getElementsByClassName('classWeb'); this gives collection & to add classes you need to iterate over them & then apply classes.
classWeb[0].className = 'webdev'; would reset class
either use classWeb[i].className += ' webdev'; or classWeb[i].classList.add('webdev');
See below working example
var button = document.getElementById('buttonWebdev');
var classWeb = document.getElementsByClassName('classWeb');
button.onmouseover = function() {
for (var i = 0; i < classWeb.length; i++)
classWeb[i].className += ' webdev';
}
.classWeb.webdev {
display: none;
}
<h3 class="classWeb">Editierbare Inhalte</h3>
<p class="classWeb">Test</p>
<button class="buttonImg" id="buttonWebdev">hover over me</button>
Firstly, the
document.getElementsByClassName('classWeb');
will give you a LIVE list of all the matched elements. That means that when you reassign the class like so:
classWeb[0].className = 'webdev';
the element will be removed from the list, as it no longer corresponds to the original command which was to find all elements with a specific class (which you overrode with 'webdev').
An easier and more friendly api is querySelectorAll which mimics the jQuery selector (which uses css selectors to find elements, thats why there is a # for an id and a . for a class name). The example below shows, how to use it.
var button = document.querySelector('#buttonWebdev');
var classWeb = document.querySelectorAll('.classWeb');
button.onmouseenter = function() {
for (var i = 0; i < classWeb.length; i++) {
classWeb[i].className = 'webdev';
}
}
ps. The querySelectorAll is not a live list, so items will not disappear after you change their class.
ps2. Use onmousenter instead of onmouseover as the onmouseenter is only called when the mouse starts hovering over an element, while onmouseover will be called on every mouse move over the element (even if already hovering).
Good luck!

Most efficient way to change class of the anchor element based on query string

Criteria - I prefer not to use any additional library, want to perform this with just pure javascript, but happy to use one if needed.
I want to add an additional class to anchor elements which have a query string of 'xyz=negate'. My page typically has more than 200 anchor elements. I am looking for the most efficient way to achieve this.
The user base for my website still has a decent number of IE 8 (intranet site) and hence looking for the most efficient code. My page has anchor elements which look like the following
Visit W3Schools.com!
Visit W3Schools.com!
Visit W3Schools.com!
Visit W3Schools.com!
Visit W3Schools.com!
I want to add class to the first, fourth and fifth anchor element in the above example.
Use * in selector to match, example:
var links=document.querySelectorAll("a[href*='xyz=negate']");
It will find all links with href containing xyz=negate in any part of attribute.
In pure js it is not possible to set class to collection like in Jquery, so we must go through every element and set class.
for ( var i in links ){
links[i].classList.add("someClass");
}
For IE8 ( classList not exists ):
for ( var i in links ){
links[i].className+="someClass";
}
Do you need to actually add the class so can you do it with just CSS?
a[href*="xyz=negate"]:first-child {
background-color: yellow;
}
If you do need the class it should just be
var elem = document.querySelector('a[href*="xyz=negate"]');
if(elem) {
elem.className = elem.className + " active";
}
If it is all, it is just
a[href*="xyz=negate"] {
background-color: yellow;
}
or
var elems = document.querySelectorAll('a[href*="xyz=negate"]');
for (var i=0;i<elems.length;i++) {
elems[i].className = elems[i].className + " active";
}
You can do this in either pure vanilla JS, or also using jQuery, if you like.
The logic and principle is still the same:
find all a anchor elements
where the href attribute contains your preferred query string ("xyz=negate") in the href
loop through the matching elements and add the class (in the examples, .someclass) to that element
Here is a JSFiddle: https://jsfiddle.net/ana4upbh/4/
I have included both the jQuery and Vanilla JS solutions for comparison; just comment/uncomment to use either
Here is a pure JS solution (IE8+ compatible):
// select all "a" (anchor) elements with the query string
var anchors = document.querySelectorAll("a[href*='xyz=negate']");
// loop through each of the matching elements
for (var i = 0; i < anchors.length; i++) {
var el = anchors[i];
// add the 'someclass' class to the element (or whatever meaningful name you use)
if (el.classList)
el.classList.add('someclass');
else
el.someclass += ' someclass';
}
or, here is a jQuery version:
$("a[href*='xyz=negate']").each(function(i) {
$(this).addClass('someclass');
});
or simply
$("a[href*='xyz=negate']").addClass('someclass');
EDIT:
Updated the selector to get desired elements, rather than doing the check within the loop, for performance; as suggested in comments. I'll update the JSFiddle when I get back on the PC JSFiddle is now up to date
EDIT 2:
Removed encapsulation of forEach loop into direct for loop, for clarity.
Added alternative jQuery solution and updated JSFiddle.
Hope this helps!
Any questions, just ask :)

add (not replace) css class using javascript

I am using a ddsmoothmenu, and it is constructed in such a way that a class name can be dynamically added to the parent menu container via the plugin, and once the class is applied to the parent container, all css will also apply on the menu.
Here is how the ddsmoothmenu is passing classname:
<div id="myMenu">
<ul>
<li>.....</li>
</ul>
</div>
And the rendering of the menu is done by the following, where the 'classname' is being passed via the plugin to be added dynamically to the menu container.
ddsmoothmenu.init({
mainmenuid: 'myMenu',
orientation: 'h',
classname: 'ddsmoothmenu',
contentsource: 'markup'
});
So far so good. But I need to add a 'noindex' class to the menu container. I thought it's easy I will simply add in the markup, but the problem is the plugin replaces my class and add whatever is supplied from the above 'classname' parameter.
In the plugin itself: this line of code is the culprit:
$mainmenu.parent().get(0).className = setting.classname || "ddsmoothmenu"
where $mainmenu is basically the unordered list.
I know I can do a simple += to concatenate classnames. But I am not sure if that is possible in the above as it has the ternary if..else setup
Can I do $mainmenu.parent().get(0).className += setting.classname || "ddsmoothmenu"
I want something like the above line so that the class that I have hard coded in the markup gets to stay while the one added by the plugin simply gets appended to the class I have added directly in the markup?
All you have to do is take the current classname, add a space to it, and add the second classname. I understand you want to use a library but plain Javascript can do this easily:
function addclass(name,id) {
var element = document.getElementById(id); //not sure how you want to obtain your element
var currentclass = element.className;
element.className = currentclass + " " + name;
}
Again, not sure how you want to select document objects but as long as you add the space between class names, all should be good.
Here is a description from the jquery api doc on the addclass function:
Description: Adds the specified class(es) to each of the set of
matched elements.
version added: 1.0.addClass( className ) className Type: String One or
more space-separated classes to be added to the class attribute of
each matched element.
version added: 1.4.addClass( function ) function
Type: Function( Integer index, String currentClassName ) => String A
function returning one or more space-separated class names to be added
to the existing class name(s). Receives the index position of the
element in the set and the existing class name(s) as arguments. Within
the function, this refers to the current element in the set.
Below is an example use of jquery's addclass function that seems to do exactly what you're asking for.
$( "p" ).last().addClass( "selected" );
(ugh keep forgetting I can't post HTML)
Essentially it just tacks on the specified class to the selected element without removing any other classes.
Here is the link to the api doc
I like to use classie. it provides a stable way to add or remove classes to to DOM. The good thing is, it provides a fallback for Browsers without the classList function (e.g. IE8).
If your just looking for the Code Snippet:
addClass = function( elem, c ) {
elem.classList.add( c );
};
and
addClass = function( elem, c ) {
elem.className = elem.className + ' ' + c;
};

javascript: Adding a class to an element that has no ID

Is there a way to add a class to an element (using pure javascript) that does not have an ID, but has some existing classes? If I had:
<div class="rightAlign pushDown">...</div>
How could I add a class to make it like this
<div class="rightAlign pushDown redOutline">...</div>
This is just a simple example. The reason for adding another class and not changing the original class in CSS or changing the class altogether with javascript is that I am dealing with elements created by Dojo. I just need to access something that has no convenient ID to grab a hold of.
Keep in mind I am working in javascript and Dojo, I can not use jQuery at all...
The dojo way would be as:
dojo.query(".rightAlign.pushDown").addClass("redOutline");
This will add the class to add elements with those two classes
var elements = document.getElementsByClassName("existing_class");
elements[0].className += " new_class";
If you want to add a class to all elements with a specified class then use a loop:
for(var i = 0; i < elements.length; i++){
elements[i].className =+ " new_class";
}
I think getElementsByClassName doesn't work in old IE versions though.
EDIT:
Polyfill for IE support

I have a nav bar that changes the src of an iframe, how can i change the active link color?

My website has a navigation bar that when clicked targets an iframe.
i would like the "active" link color to be changed.
P.S can't use jQuery, only JS and CSS.
my idea was to have an ID named ACTIVE and give the clicked link the ID active, after removing the ID from all the rest.
though i have no idea how its possible to do so.
on the other hand another option is to do the same only using a class called ACTIVE, my problem there is each link has allready a class assigned to id, and i have no idea how to remove one class out of two.
This is a problem best solved using classes. If you can't use jQuery, you can add classes in JavaScript via something like:
document.getElementById("someID").className += " newClass";
Remove a class using regex:
document.getElementById("someID").className = document.getElementById("someID").className.replace(/\bnewClass\b/,'');
If it doesn't make sense to give each link an ID, you can attach a click handler:
onclick="changeColor(this)"
And add the subsequent function:
var activeLink;
function changeColor(elem){
if(activeLink)
activeLink.className = activeLink.className.replace(/\bnewClass\b/,'');
elem.className += " newClass";
activeLink = elem;
}

Categories

Resources