Remove styles from internal style sheet using jQuery - javascript

<html>
<head>
<style>
.containerTitle {
background-color:silver;
text-align:center;
font-family:'Segoe UI';
font-size:18px;
font-weight:bold;
height:30px;
}
</style>
</head>
<body>
<div id="a"/>
</body>
</html>
How do I remove the styles applied to .containerTitle using jQuery?

A couple of options:
If you can remove the entire stylesheet (by removing the style or link element), that will remove all rules defined by that stylesheet.
Live Example:
$("input").on("click", function() {
$("style").remove(); // Your selector would be more specific, presumably
});
.red {
color: red;
}
.green {
color: green;
}
.blue {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="red">red</div>
<div class="green">green</div>
<div class="blue">blue</div>
<input type="button" value="Click to remove the stylesheet">
Alternately, if you need to just remove one rule, you can, but it's a pain: You look through the styleSheets collection to find the stylesheet object for it, then find the relevant rule in the style sheet's cssRules list (called just rules on older IE), probably by looking at each CSSStyleRule's selectorText property, then call deleteRule to delete it.
// Loop through the stylesheets...
$.each(document.styleSheets, function(_, sheet) {
// Loop through the rules...
var keepGoing = true;
$.each(sheet.cssRules || sheet.rules, function(index, rule) {
// Is this the rule we want to delete?
if (rule.selectorText === ".containerTitle") {
// Yes, do it and stop looping
sheet.deleteRule(index);
return keepGoing = false;
}
});
return keepGoing;
});
Live Example (see comments):
$("input").on("click", function() {
// Loop through the stylesheets...
$.each(document.styleSheets, function(_, sheet) {
// Loop through the rules...
var keepGoing = true;
$.each(sheet.cssRules || sheet.rules, function(index, rule) {
// Is this the rule we want to delete?
if (rule.selectorText === ".green") {
// Yes, do it and stop looping
sheet.deleteRule(index);
return keepGoing = false;
}
});
return keepGoing;
});
});
.red {
color: red;
}
.green {
color: green;
}
.blue {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="red">red</div>
<div class="green">green</div>
<div class="blue">blue</div>
<input type="button" value="Click to remove the green rule">

Personally if I was going to do something like this, I might put my css in a body element that can be easily replaced/removed. http://jsfiddle.net/oqno5643/ Changed to set with html() rather than append() to remove previous values: http://jsfiddle.net/oqno5643/1/
HTML
<div id="test">Test text</div>
<input type="button" id="changer" value="Change to Blue">
<span id="styleContainer"></span>
Javascript
$(document).ready(function(){
$('#styleContainer').html('<style>#test{ color: red; }</style>');
$('#changer').on('click', function() {
$('#styleContainer').html('<style>#test{ color: blue; }</style>');
});
});
Sorry, meant to do the html() instead of append() but forgot in my quick demo.

You can't remove the style itself but you can remove it from any element it applies to.
$('.containerTitle').removeClass('containerTitle');

Related

How to replace the entire class within the element in HTML?

I have a HTML like the below,
var divId = document.getElementById('a1');
$(divId).find('#b1').className = "red";
.green {
background-color: green;
color: #ccc;
}
.red {
background-color: red;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="a1">
<button id="b1" class="green">green</button>
</div>
<div id= "a2">
<button id ="b2" class="red">red</button>
</div>
How to replace the class Green with class red ?
You are mixing up jQuery and JavaScript here.
You can use className in a JavaScript referenced element. To change the class of a jQuery referenced element you should use .addClass(). Also, since the attribute id is unique in a DOM, simply specifying the id in the selector is enough.
$('#b1').addClass('class', 'red');
jQuery Solution:
$('#b1').addClass('red');
.Green {
background-color: green;
color: #ccc;
}
.red {
background-color:red;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id= "a1">
<button id ="b1" class = "Green">Green</button>
</div>
<div id= "a2">
<button id ="b2" class = "red">Red</button>
</div>
JavaScript Solution: Instead of using className, I will suggest you to use DOMTokenList.add() to add/remove class to an element.
var divId = document.getElementById('b1');
divId.classList.add('red');
var divId = document.getElementById('b1');
divId.classList.add('red');
.Green {
background-color: green;
color: #ccc;
}
.red {
background-color:red;
color: #fff;
}
<div id= "a1">
<button id ="b1" class = "Green">Green</button>
</div>
<div id= "a2">
<button id ="b2" class = "red">Red</button>
</div>
$(divId).find returns a jQuery object.
className is a property of HTML Element in vanilla JavaScript.
You do one of the following
the jQuery prop method, to set a property on a jQuery object.
the jQuery addClass method, to add a class on a jQuery object.
convert the jQuery object to an Element (see SO answer)
bypass jQuery itself & use querySelector instead.
This will work for you:
$("#a1 #b1").removeClass("Green");
$("#a1 #b1").addClass("red");

How do i change one of the classes in an element with Javascript

If i have the library materialize and an element "h1", how do i change only its background color "black" to "white" using javascript? For example using a button.
<h1 class="black red-text">Test</h1>
Give the element an id:
<h1 id="test" class="black red-text">Test</h1>
Then you can select it like the following:
var el = document.getElementById('test');
You can then just remove the class black with this code:
el.classList.remove('black');
And append the new class:
el.classList.add('white');
Create a function and a white class. Inside the function use document.getElementsByClassName . Since document.getElementsByClassName is a collection so you need to use index like [0] to access it
function changeColor() {
document.getElementsByClassName("black")[0].classList.add('white')
}
.white {
background: white !important;
}
.black {
background: black;
}
.red-text {
color: red;
}
<h1 class="black red-text">Test</h1>
<button onclick='changeColor()'>Change Color</button>
Here is the answer.
Select the element using document. getElementById
and on button click
You can use title.classList.toggle("white"); to toggle given class.
const button = document.getElementById('btn');
const title = document.getElementById('title');
btn.addEventListener('click', () => {
title.classList.toggle("white");
});
.red-text {
color: red;
}
.black {
background-color: #000;
}
.white {
background-color: #fff;
}
<h1 id="title" class="black red-text">Test</h1>
<button id="btn">Change Bg</button>
Hope this resolves your problem. just check the condition whether the class already exist if not add it.
let h1 = document.querySelector(".red-text");
let btn = document.querySelector("#btn");
function changeColor(){
if(h1.classList.contains("black")){
h1.classList.remove("black");
h1.classList.add("white");
}else{
h1.classList.add("black");
h1.classList.remove("white");
}
}
btn.addEventListener("click", changeColor);
.black{
background: black;
color: red
}
.white{
background: white;
}
<h1 class="black red-text">Test</h1>
<button id="btn">Change Color</button>
One approach that keeps things neat and tidy in terms of Materialize conventions could be to add or remove classnames, and thus triggering pre-existing styles. Note, you may need a more specific selector if you have multiple elements that share the class:
document.querySelector('h1.black').classList.add('white');
Materialize already has a vast array of colour classes so no need to create new ones.
Codepen here:
And just for clarification:
document.querySelector('h1.black') - this finds the element with a matching class. You could also use ID to be more specific, while
.classList retrieves all the classes applied to that element (in this case .black and .red-text) and .add('white') - well, that adds the class you state in the brackets.

jQuery - detect if div has 2 classes

I am using jQuery to detect a click like this..
$(".clickable_link").click(function() {
console.log('Link Clicked');
}
<div class="clickable_link">
Click Me
</div>
<div class="clickable_link special">
Click Me
</div>
I am trying to determine if the div with 'special' has been clicked or if it just the div with 'clickable_link'.
What is the best way to do this? Should I use hasclass or is filter a better choice?
Something like this:
$(".click").click(function(){
if ($(this).hasClass("special")) {
alert("Its Special!");
}
});
.click {
width:100px;
height:50px;
background-color:#333;
float:left;
margin:10px;
color:#fff;
text-align:center;
padding-top:25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="click">Not Special</div>
<div class="click special">SPECIAL!</div>
As an alternative to .hasClass, you can use .is, which allows for any selector, not just checking for a class.
if($(this).is(".special")) { ...
$(".clickable_link").click(function() {
if ($(this).is(".special")) {
alert("special clicked");
} else {
alert("nope");
}
});
.special { color: red; }
.clickable_link { cursor: pointer; margin-bottom: 0.5em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clickable_link">
Click Me
</div>
<div class="clickable_link special">
Click Me
</div>
$('#id1').click(function() {
var x = $('#id1').attr('class') //dont use classname to fetch the element
x = x.split(' ')
if (x.length > 2)
alert('id1 has more than 2 classes');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='id1' class='myclass mysubclass'>dfdfdfsdfds</div>
You can bind different event handlers depending on whether the special class exists.
$(".clickable_link.special").click(function()
console.log("Special link clicked");
})
$(".clickable_link:not(.special)").click(function() {
console.log("Ordinary link clicked");
});
If there's common code for both types of links, you can put that in another function that gets called by each handler.
As example, use can can detect count of classes as like it:
$(".clickable_link").click(function() {
var classList = $(this).attr('class').split(/\s+/);
console.log(`count ${classList.length}`);
}

JavaScript; Background Color change and change back w/ same input

I made this code, but it wont work. Would be nice if some one can help me. :)
I've tried many things already, but it always didn't worked.
I want it to be so that you press the button and the background gets light, when you press it again it goes back to the origin.
<html>
<head>
<title>test</title>
<style>
.darkerBG {
background: #282828;
}
.lighterBG {
background: white;
}
</style>
</head>
<body class="darkerBG" id="bdbackground">
<script language="javascript" type="text/javascript">
function changeColor()
{
var bdBackground = document.getElementById('bdbackground').class;
if (document.getElementById('bdbackground').class == 'darkerBG')
{
document.getElementById('bdbackground').class == 'lighterBG';
} else if (document.getElementById('bdbackground').class == 'lighterBG')
{
document.getElementById('bdbackground').class = 'darkerBG';
}
}
</script>
<input type="button" class="button" value="test" onclick="changeColor()">
</body>
</html>
You must use className rather than class. class is not a property on a DOM element.
You need to modify the className property on the element rather than class.
For example:
document.getElementById('bdbackground').className = 'darkerBG';
In JavaScript, the correct property is .className instead of .class. You also have an erroneous == in your assignment of document.getElementById('bdbackground').class == 'lighterBG';
Alternatively, consider using .classList.contains(...).
<html>
<head>
<title>test</title>
<style>
.darkerBG {
background: #282828;
}
.lighterBG {
background: white;
}
</style>
</head>
<body class="darkerBG" id="bdbackground">
<script language="javascript" type="text/javascript">
function changeColor() {
var myElement = document.getElementById('bdbackground');
if (myElement.className == 'darkerBG') {
myElement.className = 'lighterBG';
} else if (myElement.className == 'lighterBG') {
myElement.className = 'darkerBG';
}
}
</script>
<input type="button" class="button" value="test" onclick="changeColor()">
</body>
</html>
I have created a working solution for what you are trying to achieve. I created a JSBin with the solution and improved your code slightly: http://jsbin.com/botasehoci/1/edit?html,css,js,output
(Edit, just noticed Quantastical answered with pretty much all the issues I brought up in the time it took me to to post this answer :/ )
The main issues were that:
You needed to include the ID bdbackground on the button element.
You needed to include the initial class name on the button element ("lighterBG")
The correct way to reference the value of the class attribute is using className not class
For the first condition in the if statement, you used an comparison instead of an assignment operator ( i.e. x == a instead of x = a )
This is the updated JS:
function changeColor() {
var button = document.getElementById('bdbackground');
var buttonClass = button.className;
if (buttonClass === 'darkerBG') {
button.className = 'lighterBG';
} else if (buttonClass === 'lighterBG') {
button.className = 'darkerBG';
}
}
This is the updated HTML for the button element:
<input id="bdbackground" type="button" class="lighterBG" value="test" onclick="changeColor()">
.classList()
Use .classList.add() and .classList.remove() to toggle classes. You could use .classList.toggle() but in certain circumstances the toggled states will get discombobulated if there is more than one toggler used at the same time.
Basic Flow
When the function changeColor() is called:
Get a reference to the body with getElementById()
Find out if the body has a class called .darkerBG by using .classList.contains()
If it does have .darkerBG as a class:
Remove the class and ...
add the class .lighterBG
Otherwise:
Remove the class .lighterBG and ...
add the class .darkerBG
SNIPPET
function changeColor() {
var bG = document.getElementById('bdbackground');
if (bG.classList.contains('darkerBG')) {
bG.classList.remove('darkerBG');
bG.classList.add('lighterBG');
} else {
bG.classList.add('darkerBG');
bG.classList.remove('lighterBG');
}
}
.darkerBG {
background: rgba(20, 10, 20, .6);
transition: all 2s;
}
.lighterBG {
background: rgba(200, 100, 200, .6);
transition: all 2s;
}
<html>
<head>
<title>test</title>
</head>
<body class="darkerBG" id="bdbackground">
<input type="button" class="button" value="test" onclick="changeColor()">
</body>
</html>
Instead of using class you can use className or classList with add()/ remove() or toggle().
To check if class exists or not, you can get element attribute (class) by getAttribute('class') , then search in it using indexOf() by your class string.
For best practice try to avoid inline events and use addEventListener instead.
https://jsfiddle.net/5m5ck1fk
//btn = document.querySelector('.button');
var btn = document.getElementsByClassName('button')[0],
bdBackground = document.getElementById('bdbackground');
btn.addEventListener('click', function () {
changeColor();
});
function changeColor() {
if (bdBackground.getAttribute('class').indexOf('darkerBG') != -1) {
bdBackground.classList.remove('darkerBG');
bdBackground.classList.add('lighterBG');
} else if (bdBackground.getAttribute('class').indexOf('lighterBG') != -1) {
bdBackground.classList.remove('lighterBG');
bdBackground.classList.add('darkerBG');
}
}
.darkerBG {
background: #282828;
}
.lighterBG {
background: white;
}
<body class="darkerBG" id="bdbackground">
<input type="button" class="button" value="test">
</body>

Proper way to dynamically change css properties?

I have site that, in response to user interaction, dynamically creates divs using jquery. The div will have a span inside containing a timestamp to show its creation time, and the user can click a button to show or hide the timestamp span.
I ran into the issue of, when the user selects to hide timestamps, how do you prevent future dynamically added spans from showing? In reference to this question Create a CSS rule / class with jQuery at runtime, I added a style tag in the head dynamically. However, I also intended to allow the user to be able to choose a font from a drop down list and change the font style of the text inside the divs. Following this method now seems like it would create a lot of overhead.
Both issues revolve around the same issue: change already existing element and any future dynamically created matching element's css style, but I'm not sure the method mentioned above is really the best solution?
EDIT: SNIPPET
$(function() {
$('#add').click(function() {
$('#display').append("<div><span class='time'> ex. Timestamp</span> Div text contents...</div>");
});
$('#hidetime').click(function() {
$(this).text(function(i, text) {
if (text === "Hide Time") {
$("<style>").prop("type", "text/css")
.html(".time {display: none}").appendTo("head");
return "Show Time";
} else {
$('style').remove();
return "Hide Time";
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='add'>Add</button>
<button id='hidetime'>Hide Time</button>
<div id='display'>
</div>
You've provided no code to debug, but the way you can do this is to toggle a class such as notimestamps on the container element for the whole thing.
Then in your main CSS code you can simply do something along the lines of:
.container.notimestamps span {
display:none;
}
If you're changing font styles, you can do something very similar.
Example:
.container.font-arial {
font-family: arial, sans-serif;
}
.container.font-tahoma {
font-family: tahoma, sans-serif;
}
Using your recently added example you would change it to:
$(function() {
$('#add').click(function() {
$('#display').append("<div><span class='time'> ex. Timestamp</span> Div text contents...</div>");
});
$('#hidetime').click(function() {
$('#display').toggleClass('notimestamp');
});
$('#font').change(function() {
$('#display').attr('data-font', $(this).val());
});
});
#display.notimestamp span {
display:none;
}
#display {
font-family:sans-serif;
}
#display[data-font="arial"] {
font-family:Arial;
}
#display[data-font="georgia"] {
font-family:Georgia;
}
#display[data-font="tahoma"] {
font-family:Tahoma;
}
#display[data-font="tnr"] {
font-family:"Times New Roman";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='add'>Add</button>
<button id='hidetime'>Hide Time</button>
<select id="font">
<option value="arial">Arial</option>
<option value="georgia">Georgia</option>
<option value="tahoma">Tahoma</option>
<option value="tnr">Times New Roman</option>
</select>
<div id='display'>
</div>
You can achieve it using plain javascript
Here is an example. You can add any similar styles dynamically
HTML
<div id="myDiv" style="margin: 50px 50px 50px 50px">This is a div.</div>
<br />
<button type="button" onclick="removemargin()">remove margin</button>
<button type="button" onclick="removeLeftMargin()">remove leftmargin</button>
<button type="button" onclick="removeTopMargin()">remove topmargin</button>
<button type="button" onclick="addCssMargin()">add margin by adding class (dominant here)</button>
CSS
#myDiv {
background: #EEE;
}
.myclass{
margin : 100px 10px 15px 50px !important;
background:red !important;
}
JAVASCRIPT
function removemargin() {
document.getElementById("myDiv").style.margin = "0";
}
function removeLeftMargin() {
document.getElementById("myDiv").style.marginLeft = "0";
}
function removeTopMargin() {
document.getElementById("myDiv").style.marginTop = "0";
}
function addCssMargin() {
var d = document.getElementById("myDiv");
d.className = d.className + " myclass";
}
JsFiddle

Categories

Resources