jQuery replace one class with another - javascript

I have this jQuery and I'm changing styles in it but I've heard that the correct way to do it is to create a separate style and just replace classes with jQuery. Can you explain me how to do it correctly:
$('.corpo_buttons_asia').click(function() {
$('.info').css('visibility', 'hidden');
$('.info2').css('visibility', 'visible');
$(this).css('z-index', '20');
$(this).css('background-color', 'rgb(23,55,94)');
$(this).css('color', '#FFF');
$('.corpo_buttons_global').css('background-color', 'rgb(197,197,197)');
$('.corpo_buttons_global').css('color', '#383838');
});
$('.corpo_buttons_global').click(function() {
$('.info').css('visibility', 'visible');
$('.info2').css('visibility', 'hidden');
$(this).css('background-color', 'rgb(23,55,94)');
$(this).css('color', '#FFF');
$('.corpo_buttons_asia').css('z-index', '2');
$('.corpo_buttons_asia').css('background-color', 'rgb(197,197,197)');
$('.corpo_buttons_asia').css('color', '#383838');
});
So instead of using .css() all the time I can create another class and just replace it with jQuery.

To do this efficiently using jQuery, you can chain it like so:
$('.theClassThatsThereNow').addClass('newClassWithYourStyles').removeClass('theClassThatsTherenow');
For simplicities sake, you can also do it step by step like so (note assigning the jquery object to a var isnt necessary, but it feels safer in case you accidentally remove the class you're targeting before adding the new class and are directly accessing the dom node via its jquery selector like $('.theClassThatsThereNow')):
var el = $('.theClassThatsThereNow');
el.addClass('newClassWithYourStyles');
el.removeClass('theClassThatsThereNow');
Also (since there is a js tag), if you wanted to do it in vanilla js:
For modern browsers (See this to see which browsers I'm calling modern)
(assuming one element with class theClassThatsThereNow)
var el = document.querySelector('.theClassThatsThereNow');
el.classList.remove('theClassThatsThereNow');
el.classList.add('newClassWithYourStyleRules');
Or older browsers:
var el = document.getElementsByClassName('theClassThatsThereNow');
el.className = el.className.replace(/\s*theClassThatsThereNow\s*/, ' newClassWithYourStyleRules ');

You may use this simple plugin:
(function ($) {
$.fn.replaceClass = function (pFromClass, pToClass) {
return this.removeClass(pFromClass).addClass(pToClass);
};
}(jQuery));
Usage:
$('.divFoo').replaceClass('colored','blackAndWhite');
Before:
<div class="divFoo colored"></div>
After:
<div class="divFoo blackAndWhite"></div>
Note: you may use various space separated classes.

Sometimes when you have multiple classes and you really need to overwrite all of them, it's easiest to use jQuery's .attr() to overwrite the class attribute:
$('#myElement').attr('class', 'new-class1 new-class2 new-class3');

Starting with the HTML fragment:
<div class='helpTop ...
use the javaScript fragment:
$(...).toggleClass('helpTop').toggleClass('helpBottom');

In jquery to replace a class with another you can use jqueryUI SwitchClass option
$("#YourID").switchClass("old-class-here", "new-class-here");

You'd need to create a class with CSS -
.greenclass {color:green;}
Then you could add that to elements with
$('selector').addClass("greenclass");
and remove it with -
$('selector').removeClass("greenclass");

You can use .removeClass and .addClass. More in http://api.jquery.com.

You can use jQuery methods .hasClass(), .addClass(), and .removeClass() to manipulate which classes are applied to your elements. Just define different classes and add/remove them as necessary.

Create a class in your CSS file:
.active {
z-index: 20;
background: rgb(23,55,94)
color: #fff;
}
Then in your jQuery
$(this).addClass("active");

you could have both of them use a "corpo_button" class, or something like that, and then in $(".corpo_button").click(...) just call $(this).toggleClass("corpo_buttons_asia corpo_buttons_global");

jQuery.fn.replaceClass = function(sSearch, sReplace) {
return this.each(function() {
var s = (' ' + this.className + ' ').replace(
' ' + sSearch.trim() + ' ',
' ' + sReplace.trim() + ' '
);
this.className = s.substr(1, s.length - 2);
});
};
EDIT
This is my solution to replace one class with another (the jQuery way). Actually the other answers don't replace one class with another but add one class and remove another which technically is not the same at all.
Here is an example:
Markup before: <br class="el search-replace"><br class="el dont-search-replace">
js: jQuery('.el').remove('search-replace').add('replaced')
Markup after: <br class="el replaced"><br class="el dont-search-replace replaced">
With my solution
js: jQuery('.el').replaceClass('search-replace', 'replaced')
Markup after: <br class="el replaced"><br class="el dont-search-replace">
Imagine a string replace function in whatever language:
Search: "search-replace"
Replace: "replaced"
Subject: "dont-search-replace"
Result: "dont-search-replace"
Result (wrong but actually what the other solutions produce): "dont-search-replace replaced"
PS
If it's for sure that the class to add is not present and the class to remove is present for sure the most simple jQuery solution would be: jQuery('el').toggleClass('is-present-will-be-removed is-not-present-will-be-added')
PPS I'm totally aware that if your selector equals the class to remove the other solutions would work just fine jQuery('.search-replace').removeClass('search-replace').addClass('whatever').
But sometimes you work with more arbitrary collections.

I have used swap div to swap my video of self in thumbnail to main-video and vise versa.
I think this will help you to make a toggle between two div class.
numberId=0
function swapVideo(){
numberId++;
console.log(numberId)
if(numberId % 2 ==0){
$('#self-video').attr('class', 'main-video');
$('#trainer-video').attr('class', 'thumb-video');
}else{
$('#self-video').attr('class', 'thumb-video');
$('#trainer-video').attr('class', 'main-video');
}
}
numberId%2==0 help to keep track and perform a operation to make this toggle.

Related

How can I change a css style for 'this' class using jquery?

I have a list of images that each are tied to a class.
var hoverList = this.hoverable.getAllList() //this gets the list.
on mouseover of the images, I want a block of text in a different area, but shares a class, to display. I call
hoverList.mouseover(this.hoverable.displayTheDeets)
and it runs
displayTheDeets: function(){
big=$(".project-details")
thisClass=$(this).attr("class")
console.log(thisClass)
//$(big).find(thisClass).css("display","")
$(big).find(thisClass).css("display", "block")
//$(big > thisClass).css("display","block")
}
From the console, if I run the literal command
$(".project-details").find(".code-fusion")
it returns the element I want. And I can change the display with no problem.
I think my problem is with thisClass. Any thoughts would be appreciated.
Try,
big.find('.' + thisClass).css("display", "block");
or simply
big.find('.' + thisClass).show();
Please note that .attr('class') would return the class being used for the particular element, and it wont return the class name in the format of selector.
Additional Note: And in sometimes if you have more than one class set with that particular element then it would make the selector as invalid like $('.class1 class2 class3')
Try with prefix dot. the attr("class") returns only the name not the prefix dot.
$(big).find("."+ thisClass).css("display", "block")
or
$(big).find("."+ thisClass).show();
Try
$(big).find("."+ thisClass).css("display", "block")
Part of the problem has already been answered well enough; however, I would suggest that you solve this problem in another way.
You can define the class name separately from the class of your hovering element, e.g.
<... class="something" data-linked="theclass">
Then:
displayTheDeets: function(){
var className = $(this).data('linked');
$(".project-details").find('.' + className).show();
}

jQuery - dynamically create classes to match existing classes

I have 3 divs
<div class="box opacity1 red"></div>
<div class="box opacity.5 green"></div>
<div class="box opacity0 blue"></div>
I want to have jQuery look at the page, see these classes and then create three different classes.
opacity1{
opacity: 1
}
opacity.5{
opacity: 0.5
}
opacity0{
opacity: 0
}
So when a user adds a class, eg "opacity75" to an element. I want the jQuery script to find "opacity" and then find what number is attached to it, then use that number to create a matching css class eg. opacity75{opacity:0.75}
I have very little knowledge of JS. I need some help to start me off in the right direction.
This can save having loads of CSS classes.
var stylestring = "<style type=\"text/css\">";
$("div").each(function() {
$.each($(this).attr("class").split(" "), function () {
var class = this + " {";
//add style to string
class += "}";
stylestring += class;
});
});
stylestring += "</style>";
$(document.body).prepend($(stylestring));
This would be my approach to iterate through all classes used in divs all over the page and create the class, but you would need some kind of rule to build the style out of the actual class name at the point of //add style to string
I'm not sure how it is even possible to create CSS classes in jQuery but here is a piece of code that'll do what you're expecting
Edit
$(function() {
$('.opacity').each(function() {
$(this).css('opacity', $(this).data('opacity'));
});
});
And add data-opacity="XX" to your <div> tags.
JSFiddle
1) yor example, its not best way to set css via js
2) i think task is to set some styles to elements, so its not necessarily to create classes.
jquery can set styles to elements via .css("property","value") method
3) example of code, which might work
// get all elements which contains 'opacity' in class name
var opacityElems = $( "div[class*='opacity']" );
var elemClassName;
var elemOpacityValue;
// cycle through all this elements
opacityElems.each(function(i,elem) {
// write the class name of the current element as a string
elemClassName = $(elem).attr('class');
// remove first 7 simbols, so only last numbers left
elemOpacityValue = elemClassName.substring(7, elemClassName.length);
// because obtained in the previous one step is a string, then give her number
// ie "0.12" to 0.12
elemOpacityValue *= 1;
// set style to element
$(elem).css("opacity",elemOpacityValue);
})
p.s. i am sorry for the mistakes - English is not the native language

setting color of a link in javascript

I want to set the color of "val" in the link in below code.
var link = $('' + val + '<br><br>');//this is the link
link.style.color="red";//this is how iam trying to set the color of "val"
SO HOW TO EXACTLY DO IT.
You can do this:
link.css({ color: 'red' });
But the correct and nice way would be:
$(".parent_element").prepend(''+val+'<br><br>');
$(".parent_element > a:first").css({ color: 'red' });
Try this:
$(link[0]).css({ color: 'red'});
The reason for this is that link is not an <a> element - it's a set of elements: <a>, <br> and another <br>.
Another approach would be:
link.css({ color: 'red' });
but this will set this CSS to not only <a>, but both <br>'s as well (not a big deal though).
If you are using jQuery(which it does seem like) go ahead with this,
jQuery
link.css("color","red");
Otherwise,
JavaScript
link[0].style.color = "red";
What you did doesn't work because link is an array. Before applying a style to it, you have to first select the first element by link[0] and then operate on it.
You could use link.style.color="red" if link was an HTMLElementNode, but it isn't. It might be a jQuery object, but if you are using an older version of the library then it will return undefined.
First you need to fix your jQuery call. You can't create multiple elements at the top level. (You can skip this bit if you are using a sufficiently new version of jQuery).
Since there is no good reason to use a double <br> (it shouts "Use CSS to add a margin instead"), I've taken them out:
var link = $('' + val + '');
Now you have a jQuery object so you can either use the jQuery method of setting CSS:
link.css("color", "red");
or get the HTMLElementNode from the jQuery object and use that:
link.get(0).style.color="red";
link.css("color", "red")
However, I think it would be better to create a css class for that and set up the color there. In Javascript/jQuery I would just add the class to the tag when needed. It is more elegant.

how to check if a div has a class out of multiple classes in jquery

I have a dynamic div which can generate over 1000 different classes... its a wordpress theme.
Now i am wanting to check if a div has one of 52 classes.
.bg1, .bg2, .bg3 etc etc...
I know that you can use hasClass();
But how do I check for each one and then get the value. For instance here is the div as it stands
<div id="wordpresspost" class="bodyclass post-id-193 wordpresswrap bg1"></div>
Please bare in mind I dont really know jquery :D
I was thinking it would be something like this but logically this does not make sense to me :(
var divclass = $("#wordpresspost").hasClass('bg1, bg2, bg3, bg4, bg5, bg6');
if(divclass == true){
var divsclass = $(this);
}
I need to know the class because I want to change it, for instance i would like to .removeClass and then addClass a new class without changing the others as they are dynamic
Thanks in advance for the advice :)
Use .is():
var divclass = $("#wordpresspost").is('.bg1, .bg2, .bg3, .bg4, .bg5, .bg6');
You can use starts with selector.
Caveat with this is that if you have another class starts with bg[something] it would be impacted
if($("#wordpresspost[class^=bg]").length > 0)
{
....
}
In order to remove it probably regex might help.
$("#wordpresspost[class^=bg]").each(function(){
this.className = this.className.replace(/\bbg.*?\b/g, 'newclass');
});
var el = document.getElementById('wordpresspost');
var regxpr = /\b(bg(?:[1-9]|[1-4]\d|5[0-2]))\b/g, match;
while(match = regxpr.exec(el.className)){
// match[1] contains the current matching class
console.log(match[1]);
// Then you can do:
$(el).removeClass(match[1]).addClass(replacementForMatch);
}
JSFiddle
If you are searching for bg* in only one element, you could just use simple regex.
var hasBg = /bg[\d]+/.test(document.getElementById("mydiv").className);

Remove tag around a text node using javascript

If I have some HTML that looks like this:
<div id="text">
This is some text that is being written <span class="highlight">with
a highlighted section</span> and some text following it.
</div>
And I want to remove the "span" leaving the text node within, how would I go about doing that? I tried using jQuery to do the following:
wrap = $('.highlight');
wrap.children().insertBefore(wrap);
wrap.remove();
But that doesn't work I'm guessing because children returns an empty set since there's only a text node in there. So all that happens is that the span and its contents are removed.
I'm also open to alternatives to my approach here. What's happening is that my code actually creates that span when a user selects a block of text. It wraps the selected text in a span to visually differentiate it. I need to remove the span afterward though because of some quirks with the way mozilla's range object works.
EDIT: I don't want to replace the entire content of '#text' by the way since it could be very large.
You get the text, and replace the span with it:
var wrap = $('.highlight');
var text = wrap.text();
wrap.replaceWith(text);
wrap it in a plugin
(function($) {
$.fn.tagRemover = function() {
return this.each(function() {
var $this = $(this);
var text = $this.text();
$this.replaceWith(text);
});
}
})(jQuery);
and then use like so
$('div span').tagRemover();
Working Demo here - add /edit to the URL to play with the code
This works:
wrap = $('.highlight');
wrap.before(wrap.text());
wrap.remove();
This will do what you want, and also preserve any tags within the .highlight span.
content = $(".highlight").contents();
$(".highlight").replaceWith(content);
element = document.getElementById("span id");
element.parentNode.insertBefore(element.firstChild, element);
element.parentNode.removeChild(element);
text.replace(/</?[^>]+(>|$)/g, "");
it would be much easier to just change the class of the span than to actually remove it. You can use pure javascript:
document.getElementById("span id").className="";
Or jquery's toggleClass function:
$("element").toggleClass("highlight");
Also, best practices say that you shouldn't use class names that imply a style, like highlight. Try "emphasized" instead. :D
A better unwrap plugin:
$.fn.unwrap = function() {
this.parent(':not(body)')
.each(function(){
$(this).replaceWith( this.childNodes );
});
return this;
};
from Ben Alman

Categories