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

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");

Related

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.

How to set background color for all elements with the same class individually based on custom attribute

I have multiple elements with the class .hours and they all have a color attribute with a hex value like so: <div class="hours" color="#FFFFFF">.
How can I use jQuery to set the background color of all the elements individually so that the element over has the color #FFFFFF and the element <div class="hours" color="#666666"> gets the background color #666666?
My attempt: $('.hours').css('background-color', this.attr.color);
You can use .each to refer to every element and it's color attribute
$('.hours').each(function() {
let elem = $(this);
elem.css('background', elem.attr('color'));
});
.hours {
border: 1px solid black;
height: 100px;
width: 100px;
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hours" color="#FFFFFF"></div>
<div class="hours" color="#AAAAAA"></div>
<div class="hours" color="#444444"></div>
Pure JS solution (for this jQuery is rather ineffective in my opinion...):
document.querySelectorAll('.hours').forEach(function(el) {
el.style.backgroundColor = el.getAttribute('color');
});
try with this
$('.hours').each(function(){
var t = $(this);
t.css('background-color', t.attr('color'));
});
})
$(".hours").each(function(){
let $this= $(this);
let color=$this.attr("color");
$this.css("background-color", color);
});
Not really what you asked, but the same can be achieved without JS, just with pure CSS and custom properties:
<div style="--color: green"></div>
div {
--color: #e2001a; /* default color */
background-color: var(--color);
height: 40px;
}
Example: http://jsfiddle.net/e1fwtcdz/1

Javascript - show a button inside of a DIV when clicked (and hide all others)

I have a list of DIVS that have buttons inside. By default, all buttons are hidden. When I click within a DIV area, the current button inside of this clicked DIV are should show (class='.db') AND all previously clicked/shown buttons should be hidden (class='.dn'). In other words, at any time there should be only one button (currently clicked) shown and all other should be hidden.
I want to use vanilla Javascript and tried this below, but it won't work. I feel there is some small error but don't know where.. Note - the DIVS and buttons don't have their own unique IDs (they only have the same CSS (.posted) classes.
PS - maybe it'd be better not to add this onClick="t();" to each DIV and use an 'addEventListener' function, but this is way too much for me ; )
CSS:
.dn {display:none}
.db {display:block}
.posted {
height: 50px;
width: 100px;
background-color: green;
border: 2px solid red;
}
HTML:
<div class="posted" onClick="t();">
<button class="dn">Reply</button>
</div>
<div class="posted" onClick="t();">
<button class="dn">Reply</button>
</div>
<div class="posted" onClick="t();">
<button class="dn">Reply</button>
</div>
JAVASCRIPT:
function t()
{
var x=document.getElementsByClassName("posted"),i,y=document.getElementsByTagName("button");
for(i=0;i<x.length;i++)
{
x[i].y[0].className="dn";
};
x.y[0].className='db';//make sure the currently clicked DIV shows this button (?)
}
You might want to read more about selector, how to select class, block level etc.
some link might be helpful:
CSS selector:
https://www.w3schools.com/cssref/css_selectors.asp
jQuery selector:
https://api.jquery.com/category/selectors/
Solution - Using jQuery:
$('.posted').on('click', function() {
//find all class called posted with child called dn, then hide them all
$('.posted .dn').hide();
//find this clicked div, find a child called dn and show it
$(this).find('.dn').show();
});
.dn {
display: none
}
.db {
display: block
}
.posted {
height: 50px;
width: 100px;
background-color: green;
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="posted">
<button class="dn">Reply1</button>
</div>
<div class="posted">
<button class="dn">Reply2</button>
</div>
<div class="posted">
<button class="dn">Reply3</button>
</div>
Solution - Pure js version:
//get list of div block with class="posted"
var divlist = Array.prototype.slice.call(document.getElementsByClassName('posted'));
//for each div
divlist.forEach(function(item) {
//add click event for this div
item.addEventListener("click", function() {
//hide all button first
divlist.forEach(function(el) {
el.getElementsByTagName('button')[0].classList.add('dn');
});
//show button of the div clicked
this.getElementsByTagName('button')[0].classList.remove('dn');
}, false);
});
.dn {
display: none
}
.db {
display: block
}
.posted {
height: 50px;
width: 100px;
background-color: green;
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="posted">
<button class="dn">Reply1</button>
</div>
<div class="posted">
<button class="dn">Reply2</button>
</div>
<div class="posted">
<button class="dn">Reply3</button>
</div>
You can do this with with plain JavaScript using Event Bubbling, querySelector and the element classList attribute like this.
Change your HTML to look like this:
<div class="posts">
<div class="posted">
<button class="dn">Reply</button>
</div>
<div class="posted" >
<button class="dn">Reply</button>
</div>
<div class="posted" >
<button class="dn">Reply</button>
</div>
</div>
Then use JavaScript like this:
var posts = document.querySelector('.posts');
var allPosted = document.querySelectorAll('.posted');
//clicks bubble up into the posts DIV
posts.addEventListener('click', function(evt){
var divClickedIn = evt.target;
//hide all the buttons
allPosted.forEach(function(posted){
var postedBtn = posted.querySelector('button');
postedBtn.classList.remove('db');
});
// show the button in the clicked DIV
divClickedIn.querySelector('button').classList.add('db')
});
You can find a working example here: http://output.jsbin.com/saroyit
Here is very simple example using jQuery .siblings method:
$(function () {
$('.posted').click(function () {
$('button', this).show();
$(this).siblings().find('button').hide();
});
});
https://jsfiddle.net/3tg6o1q7/

JQuery:Selecting second element in case element with same ID exists

I know it's not a good practice to use same id for different element , but in a case I am forced to use same id for two different elements ( which will be automatically generated in the original program)
I'm trying to select the second element with the same id ( or when scaling say , nth element ).
Is there a way to do this ?
I have created a code snippet here , that shows the problem.
$("#btn").click(function(){
$("#test").css("background","blue");
});
#test {
height: 100px;
width: 100px;
border: 1px solid #ccc;
margin:10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>
<div id="test">
</div>
<button id="btn">Click Me</button>
You must not have duplicate ids but if you can not do that you can use Attribute Equals Selector [name=”value”] with :eq(index). The :eq takes the index of element of the collection. You may also want to use background-color.
Live Demo
$("[id=test]:eq(1)").css("background-color","blue");
Try using the data-id attribute instead since duplicate ids can produce unpredictable behaviour.
$("#btn").click(function(){
$("[data-id='test']:eq(1)").css("background","blue");
});
[data-id='test'] {
height: 100px;
width: 100px;
border: 1px solid #ccc;
margin:10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-id="test">
</div>
<div data-id="test">
</div>
<button id="btn">Click Me</button>
$("#test:eq(1)").css("background-color","blue");

Remove styles from internal style sheet using jQuery

<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');

Categories

Resources