removeAttribute removes all other classes associated with element [duplicate] - javascript

This question already has answers here:
How can I change an element's class with JavaScript?
(33 answers)
Closed 5 years ago.
I am trying to use removeAttribute() to remove one specific class attribute from an element. The problem is that removeAttribute() seems to remove all of the other defined class attributes on the element.
Example:
HTML
<span id="click">Click</span>
<div id="box" class="blue dotted width-50"></div>
CSS
.blue {
background-color: blue;
}
.dotted {
border: thin dotted grey;
}
.width-50 {
width: 50px;
height: 50px;
}
JS
var el = document.getElementById('click');
el.addEventListener("click", removeColor, false);
function removeColor() {
var box = document.getElementById('box');
box.removeAttribute('class', 'blue');
}
How can I just remove the one class attribute from the element, without affecting the other class attributes on the element?
http://jsbin.com/xoxodezeze/edit?html,css,js,output

You need to use
function removeColor() {
var box = document.getElementById('box');
box.classList.remove('blue');
}
The problem is that removeAttribute() removes the complete attribute name class
SO <div id="box" class="blue dotted width-50"></div>
becomse like <div id="box" ></div>.
You just want to remove the class here is doc
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

Related

How can I change the background color of element in an array

I have an array of 5 divs
`<div id="cap-left2"</div>`
`<div id="cap-left1"</div>`
`<div id="cap-base"</div>`
`<div id="cap-right1"></div>`
`<div id="cap-right2"</div>`
all these divs have a background .
In my javascript I have :
let items = [capBase,capLeft1,capLeft2,capRight1,capRight2];
this works :
`var tom = items[Math.floor(Math.random()*items.length)]
console.log(tom)`
and this works
`var tom = items[Math.floor(Math.random()*items.length)]`
`console.log(tom.style)`
but I want the backgroundColor and neither of these work:
`var tom = items[Math.floor(Math.random()*items.length)]`
`console.log(tom.style.background)`
`var tom = items[Math.floor(Math.random()*items.length)]`
`console.log(tom.style.backgroundColor)`
what I am trying to do is lets say i have 5 swatches represented by 5 elements in an array . i want to be able to have a button that allows me to randomize what colors fill each element
any help would be appreciated
element.style represent style of the element, it will only be populated if style attribute is present (aka in-line style), CSS style will not affect that object.
So, element.style.backgroundColor will be empty, unless element has style="background-color: red;" as an attribute.
If you need get actual rendered style of an element, use
window.getComputedStyle(element).backgroundColor
document.querySelectorAll("div").forEach( div =>
{
console.log("style: " + div.style.backgroundColor, "final: " + window.getComputedStyle(div).backgroundColor, div);
});
body > div[id]
{
width: 1em;
height: 1em;
background-color: green;
border: 1px solid black;
}
<div id="cap-left2"></div>
<div id="cap-left1" style="background-color: red;"></div>
<div id="cap-base"></div>
<div id="cap-right1"></div>
<div id="cap-right2"></div>
const xx = window.getComputedStyle(searchBtn).getPropertyValue('background-color')
console.log(xx)
you can access only inline css proprty values via styleproperty. You need getComputedStyle

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.

getComputedStyle() Unexpected Behaviour [duplicate]

This question already has answers here:
text-decoration: apparent discrepancy between appearance and computed values
(3 answers)
Closed 7 years ago.
In the following code example, I'd expect to see underline in the console log. Instead, I see none.
How do I extract the underline value from the text-decoration property in #one .yo?
setTimeout(function() {
var $el = document.querySelectorAll('#one .yo')[0];
var css = getComputedStyle($el).cssText;
console.log("text-decoration is set to:");
console.log(/text\-decoration\: ([^\;]+)/g.exec(css)?.[1] + '!');
console.dir($el);
console.log(window.getComputedStyle($el));
var $el2 = document.querySelectorAll('#two .yo')[0];
$el2.style.cssText = css;
}, 750);
* {
margin: 0;
padding: 0;
}
#one {
color: blue;
text-decoration: underline;
}
<div id="one">
<div class="yo">what's up</div>
</div>
<div id="two">
<div class="yo">what's up</div>
</div>
Although it affects its childs, the text-decoration style property [of the parent] is not inherited (bold is mine):
The text decorations are not technically inherited, but the effect is similar to inheritance. If they’re set on an inline element, they apply to all boxes generated by that element. (...)
It seems strange because other similar properties, like font-size, do inherit, but that's just the way it is (see "Inherited: no" at the table here and/or here).

Is there any possibility to work with all elements of the same class except 'this' in JS and jQuery [duplicate]

This question already has answers here:
how to select all class except the clicked element in JQuery?
(3 answers)
Closed 7 years ago.
When I use this for various elements of same class, is there any possibility in JS/ jQuery to work with something like all elements except that one selected in order to write less code?
$('.field').focus(function() {
$(this).css('border-bottom','3px solid red');
$(all other elements of the class .field). $(this).css('border-bottom','3px solid grey');
});
You can use .not(this)
var fields = $('.field').focus(function() {
fields
.css('border-bottom','3px solid grey')
.not(this).css('border-bottom','3px solid red');
});
Added a simple example using .not below to illustrate how it works. Hope this helps
var fields = $('.field').on('click', function() {
fields
.css('border','3px solid grey')
.not(this).css('border','3px solid red');
});
.selected {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field">One</div>
<div class="field">Two</div>
<div class="field">Three</div>
<div class="field">Four</div>
<div class="field">Five</div>
For this specific scenario, you can also do something like this without .not()
var fields = $('.field').focus(function() {
fields.css('border-bottom','3px solid grey');
$(this).css('border-bottom','3px solid red');
});

How change content value of pseudo :before element by Javascript [duplicate]

This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
Closed 2 years ago.
I have the grap constructured by CSS, which is dynamically changes by JS. I show graph max value by pseudo element as:
.graph:before {
content:""; //value that want set by JS
position:absolute;
top:0;
left:0;
}
That's why I need to set this value by JS. I tried $(".graph:before").css("content", hh); but it didn't help. How to get that value?
I hope the below snippet might help, you can specify the content value you want via JS using the CSS attr() function.
Below you have two options: to use JavaScript or jQuery:
jQuery:
$('.graph').on('click', function () {
//do something with the callback
$(this).attr('data-before','anything'); //anything is the 'content' value
});
JavaScript:
var graphElem = document.querySelector('.graph');
graphElem.addEventListener('click', function (event) {
event.target.setAttribute('data-before', 'anything');
});
CSS:
.graph:before {
content: attr(data-before); /* value that that refers to CSS 'content' */
position:absolute;
top: 0;
left: 0;
}
Update (2018): as has been noted in the comments, you now can do this.
You can't modify pseudo elements through JavaScript since they are not part of the DOM. Your best bet is to define another class in your CSS with the styles you require and then add that to the element. Since that doesn't seem to be possible from your question, perhaps you need to look at using a real DOM element instead of a pseudo one.
You can use CSS variable
:root {
--h: 100px;
}
.elem:after {
top: var(--h);
}
let y = 10;
document.documentElement.style.setProperty('--h', y + 'px')
https://codepen.io/Gorbulin/pen/odVQVL
I believe there is a simple solution using the attr() function to specify the content of the pseudo element. Here is a working example using the 'title' attribute, but it should work also with custom attributes.:
document.getElementById('btn_change1').addEventListener("click", function(){
document.getElementById('test_div').title='Status 1';
});
document.getElementById('btn_change2').addEventListener("click", function(){
document.getElementById('test_div').title='Status 2';
});
#test_div {
margin: 4em;
padding:2em;
background: blue;
color: yellow;
}
#test_div:after {
content:attr(title);
background: red;
padding:1em;
}
<button id='btn_change1'>Change div:after to [Status 1]</button>
<button id='btn_change2'>Change div:after to [Status 2]</button>
<div id='test_div' title='Initial Status'>The element to modify</div>
People who are still looking some solution of same problem, it is doable as follows using jQuery:
<button id="changeBefore">Change</button>
<script>
var newValue = '22';//coming from somewhere
var add = '<style>.graph:before{content:"'+newValue+'"!important;}</style>';
$('#changeBefore').click(function(){
$('body').append(add);
});
</script>
This example illustrate that on clicking button: changeBefore , the value for .graph:before will change as per new dynamic coming value for it.
For more description about changing of :before or :after element style or getting its content:
Lets suppose your HTML is like this:
<div id="something">Test</div>
And then you are setting its :before in CSS and designing it like:
#something:before{
content:"1st";
font-size:20px;
color:red;
}
#something{
content:'1st';
}
Please notice I also set content attribute in element itself so that you can take it out easily later.
Now there is a button clicking on which, you want to change the color of :before to green and its font-size to 30px. You can achieve that as follows:
Define a css with your required style on some class .activeS :
.activeS:before{
color:green !important;
font-size:30px !important;
}
Now you can change :before style by adding the class to your :before element as follows:
<button id="changeBefore">Change</button>
<script>
$('#changeBefore').click(function(){
$('#something').addClass('activeS');
});
</script>
If you just want to get content of :before, it can be done as:
<button id="getContent">Get Content</button>
<script>
$('#getContent').click(function(){
console.log($('#something').css('content'));//will print '1st'
});
</script>
I hope it helps
I had a similar problem, but with icons. I needed to switch the play and pause icons for an audio player in html5.
The problem here was that HTML, CSS and jQuery all interpret differently the "content" values to show icons, due to the use of \ symbol.
So the best workaround is to delete and re-create the node. Here's my code:
<ul class="list list--buttons">
<li><i class="fa fa-step-backward"></i></li>
<li><i class="fa fa-play"></i></li>
<li><i class="fa fa-step-forward"></i></li>
</ul>
And the script
<script type="text/javascript">
$(
function(){
var aud = $('audio')[0];
$('.playpause').on('click', function(e){
e.preventDefault();
if (aud.paused) {
aud.play();
/* from play icon to pause icon */
$('.playpause .fa-play').remove();
$('.playpause').append('<i class="fa fa-pause"></i>');
}
else {
aud.pause();
/* from play icon to pause icon */
$('.playpause .fa-pause').remove();
$('.playpause').append('<i class="fa fa-play"></i>');
}
})
$('.next').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
$('.previuos').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
aud.ontimeupdate = function(){
$('.progress').css('width', aud.currentTime / aud.duration * 100 + '%')
}
})
</script>
Hope it helps!
You can use document.styleSheets to modify pseudo selector cssRules
document.styleSheets[0].cssRules[0].style.content = '"111"';
If you use something like an onoffswitch and want to translate the css content attribute with i18next then you can use one of the i18next Framework example from github (i18next Jquery Framework) and then you extended the function with this code:
var before = i18next.t('onoffswitch.before');
var after = i18next.t('onoffswitch.after');
$('.onoffswitch-inner')
.attr('data-before', before )
.attr('data-after', after );
and the css code must be this:
.onoffswitch-inner:before {
content: attr(data-before);
padding-left: 10px;
background-color: #65AFF5; color: #FFFFFF;
}
.onoffswitch-inner:after {
content: attr(data-after);
padding-right: 10px;
background-color: #EEEEEE; color: #999999;
text-align: right;
}

Categories

Resources