How do you remove CSS style inside a style element? - javascript

Example:
<style>
.className {
left: 0;
color: blue;
}
</style>
I want to remove the left: 0; aspect using javascript/jquery or whatever method I have to use to do this. I don't have the option of opening the document to edit or delete. Any Ideas? Note that this class has other styles within it and I just want to remove the left:0; aspect ONLY leaving the rest intact.

An element's style attribute can override its CSS class properties. left: auto will also reset the left property of an element to the default value.
An element's style can be set like this in Javascript:
Element.style.[CSS property] = [value]
<span id="someId">Span</span>
<script>
document.getElementById("someId").style.color = "#aeb";
</script>
Its jQuery equivalent is (for one CSS property):
$([selector]).css([CSS property], [value]);
$('#someId').css("color", "#aeb");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="someId">Span</span>
For many CSS properties:
$([selector]).css({[CSS property]: [value], [CSS property]: [value]});
$('#someId').css({"color":"red", "font-size":"1.5em", "position":"absolute", "top": "25%", "left": "25%"});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="someId">Span</span>
<style>
.className {
left: 0;
position: absolute;
}
</style>
<span class="className">Span.className</span><br/>
<span class="className">Span.className</span><br/>
<span class="className">Span.className</span><br/>
<span class="className">Span.className</span><br/>
<span class="className">Span.className</span><br/>
<span style="left: 0; position: absolute;">Span with left:0 and position:absolute</span>
<script>
var elems = document.getElementsByClassName("className");
for(let i = 0; i < elems.length; i++){
elems[i].style.left = "50px";
}
</script>
To overwrite all previous set CSS properties of an element, you can use all: initial, setting all CSS properties to its initial value.
<style>
.someClass{
position: fixed;
color: red;
background-color: dodgerblue;
font-size: 3em;
margin: 20px;
}
</style>
<span class="someClass">Span.someClass</span>
<span class="someClass" style="all: initial;">Span.someClass all:initial</span>

left:auto;
Auto will reset the left attribute to the browser's default for the page :)
possible / similar duplicate:
How to remove Left property when position: absolute?

Using jquery you should be able to simply do this:
$('.className').css({'left': 'auto'});
Or, if the class isn't really all that important anyways, you could just remove it like this:
$('.className').removeClass('className');
You could override it with another value either in CSS, or using the same jQuery thing mentioned in the first part of my answer.

Here are two different approaches.
1. Replace/Remove the class
If that is the only style attribute in that class, you could remove the class from all elements that use it.
Example with jQuery:
$(".className").removeClass("className").addClass("anotherClass");
2. Override the attribute
The default value for left in CSS is auto, so you could override the CSS for all of those elements.
Example with jQuery:
$(".className").css("left", "auto");

Try like this:
$('.className').remove();

Since it has a value, making the value blank will make it so it doesn't count as any value and the css attribute will be skipped/ignored.
Solution:
$('.className').css('left',' ');
If the attribute still gets read as 0 then you will have to apply the !important to the .css(); to override it.

Related

How to apply a class to elements based on their z-Index value? (using javascript)

I'm trying to change the opacity of all elements on my document, except for the one I clicked (which has the highest z-Index).
Here is the code I'm using, am I accessing the z-Index's wrongly? When run, the opacity of the whole page changes (including those with a z-Index higher than 6).
allElements = document.getElementsByTagName("*")
for (let i = 0; i < allElements.length; i++) {
if (allElements[i].style.zIndex < 6)
allElements[i].style.opacity='0.7'
}
I would suggest a cleaner and more robust approach based on classes.
Basically use event listeners and toggle classes on your body and your highlightable items. The rest is just CSS as you would imagine.
resetAllHighlights = () => [...document.querySelectorAll('.item')].map(e => e.classList.remove('highlighted'));
toggleHighlightMode = (highlightMode) => {
if (highlightMode) document.querySelector('body').classList.add("highlight-enabled");
else document.querySelector('body').classList.remove("highlight-enabled");
return highlightMode = !highlightMode;
};
[...document.querySelectorAll('.item')].map(e => e.addEventListener('click', (e) => {
resetAllHighlights()
toggleHighlightMode(true)
e.currentTarget.classList.add('highlighted');
}));
.item {
height:100px;
width: 100px;
background-color: red;
margin: 5px;
opacity: 1;
}
body {
display: flex;
}
body.highlight-enabled .item:not(.highlighted) {
opacity: 0.5;
}
<body class="">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</body>
When you access an element's .style property, you will only have access to the styles that were established on the element via the HTML style attribute. If the styling was done via the class attribute or set with JavaScript, the .style property won't be able to access it. In those cases, you must use .getComputedStyle(), which doesn't care how or where the styling was set.
And speaking of how to set styles, it's always better to set styles using pre-made CSS classes and then just add or remove the class(es) as needed instead of setting individual styles. Using classes reduces duplication of code, is easier to manage, and scales better. You can easily access and add, remove or toggle classes with the .classList API.
Also (FYI), don't use .getElementsByTagName() as this is a legacy method that returns a "live node list", which can hurt performance. Instead, use .querySelectorAll()
So, here's an example similar to what you are doing:
let divs = document.querySelectorAll("div.opaque");
// Just set up one event handler at a common ancestor of
// all the elements that may trigger the event
document.addEventListener("click", function(event){
// Check to see if the event was triggered by
// an element you care to handle
if(event.target.classList.contains("opaque")){
// Loop over all the necessary elements
divs.forEach(function(div){
// Check the z-index using .getComputedStyle()
if(getComputedStyle(div).zIndex < 6){
// Instead of modifying a style directly,
// just add a pre-made class
div.classList.add("lightOpaque");
}
});
}
});
body { background-color: red; }
div { height:35px; border:1px dotted grey; position:relative; z-index:5; background-color:skyblue; }
.lightOpaque { opacity: .7; }
.special { position:relative; z-index:7; background-color:aliceblue; }
<div class="opaque">
</div>
<div class="opaque">
</div>
<div class="opaque special">
</div>
<div class="opaque">
</div>
<div class="opaque">
</div>
<div class="opaque">
</div>

Retrieve CSS value, not inline-style value

In Javascript, can I retrieve the CSS values of an element without taking account of its inline style?
example:
body { font-size: 15px; }
<body style="font-size: 20px;">
Is there a way I can retrieve "15px" and not "20px"?
Yes, of course! Just get rid of the style attribute, use getComputedStyle(), and add the style attribute back:
//Get the body's style attribute:
var bodyStyle = document.body.getAttribute("style");
//Now, get rid of it:
document.body.removeAttribute("style");
//Now use getComputedStyle() to compute the font size of the body and output it to the screen:
document.write( getComputedStyle(document.body).fontSize );
//Now add the style attribute back:
document.body.setAttribute("style", bodyStyle);
body { font-size: 15px; }
<body style="font-size: 20px;">
</body>
var a = document.getElementsByTagName('body');
console.log (a[0].attributes.style); // returns the current inline style
a[0].setAttribute('style','font-size : 15px'); // change it as required

Change CSS Property through JavaScript. (Uses ID's and Classes)

I'm trying to resize a panel using JavaScript to fit a small image into a panel, and struggling badly.
It's within the bold:
<body id="visCinemaTransRefund"><br>
<div id="content"><br>
<ul class="PayPanel" id="paymentDetails"><br>
Here's the CSS that needs modifying:
visCinemaTransRefund .PayPanel { width: 435px; }
How would I be able to modify with width of this panel?
I've also got a form I'm trying to resize within CSS:
visCinemaTransRefund FORM (width: 1005px;)
document.getElementById('paymentDetails').style.width = '1000px';
Have you tried using:
document.getElementById("paymentDetails").getElementsByClassName("PayPanel")[0].style.width="1000px"
Remember: getElementsByClassName return an array of elements, so using [0] you are indexing first element (and, of course, the only one).
Since getElementsById return a single elements, getElementsByClassName could be useless.
If you want to do this using CSS class :
HTML:
<div id="myDiv" class="medium"></div>
<button id="btn">Click me</button>
CSS:
#myDiv {
background-color: gray;
}
.medium {
height: 50px;
width: 50px;
}
.big {
height: 100px;
width: 100px;
}
JS:
document.getElementById("btn").onclick = function() {
var element = document.getElementById("myDiv"); // or document.getElementsByClassName("className")
if (element.className == "medium") {
document.getElementById("myDiv").className = "big";
} else {
document.getElementById("myDiv").className = "medium";
}
};
JSFIDDLE
Use the following code to change the width of tags by accessing HTML element from the DOM using getElement functions and setting width to it using setAttribute javaScript function.
document.getElementById("paymentDetails").setAttribute("style","width:500px;");
document.getElementById("visCinemaTransRefund").getElementsByTagName("form")[0].setAttribute("style","width:1000px;");
Using JavaScript:
document.getElementById('paymentDetails').style.width = '1000px';
Using JQuery:
$("paymentDetails").width(1000);
$("paymentDetails").css("width","1000px");

grouping inside a for loop & modifying span elements according to style attribute

I have a set of span elements on a page. They are positioned with some information that they receive from the backend and the style attribute is changed accordingly with a previous javascipt execution.
It's like a map.
On the map there are several spots and every spot has a name.
But some spots might have several names.
<span class="myimages" id="tag-14" style="position: absolute; left: 191px; top: 217px;">hello</span>
<span class="myimages" id="tag-15" style="position: absolute; left: 141px; top: 112px;">bye</span>
<span class="myimages" id="tag-16" style="position: absolute; left: 191px; top: 217px;">welcome</span>
<span class="myimages" id="tag-17" style="position: absolute; left: 50px; top: 12px;">lunch</span>
What I want to do is I want to create groups inside this array of objects so that I can modify them as I wish.
I want to do something like creating an array and then getting the ones who share the same attribute (same position) and then do something which only would affect that group of span elements but not the other ones.
The first part I'm able to fulfill :
function foam()
{
var menus = document.getElementsByClassName("myimages");
for (var i=0; i < menus.length ; i++)
{
menuposition = menus[i].getAttribute("style");
menus[i].setAttribute('style', menuposition+'background-color:pink;');
}
}
But this ofcourse changes the style attribute of every element, I want to be able to make a loop inside a loop, or create conditions or something to fulfill this.
Thanks in advance.
UPDATE:
I can't assign a class name automatically. The position information is coming from a flat list of like: "spot name, spot names coordinate on the image" and only info that tells that one spot is the same is the x & y coordinate... It's somehow limiting but it's the case.
Also I'd be modifying a few attributes more than changing just the background color.
First, you shouldn't use the style attribute to actually change the style of an element. You should use the style object property, so you do:
menus[i].style.backgroundColor = "pink";
And this keeps the remaining style properties, since they're all listed in the style object. And even if you want the list of all the style properties set, you can use menus[i].style.cssText, which isn't available in older IE (<8 IIRC), but that won't be a problem since I see you're using getElementsByClassName.
Then, let's see your problem. If you think you can rely on the <span> coordinates, you can filter them out like this:
var menus = document.getElementsByClassName("myimages");
for (var i=0; i < menus.length ; i++) {
if (menus[i].style.left === x + "px" && menus[i].style.top === y + "px") {
menus[i].style.backgroundColor = "pink";
}
}
This assigns the background color "pink" to all those images the have the same left and top style properties (equal to x and y pixels). Maybe it isn't exactly what you want (please explain it a little more), and maybe you may want to limit the condition to the left property only, or top.
But my advice in the end is to set another style class to the elements so that all the work can be made easier, or even totally via CSS. Just to be clear:
<span class="myimages group-1" id="tag-14">hello</span>
<span class="myimages group-2" id="tag-15">bye</span>
<span class="myimages group-1" id="tag-16">welcome</span>
<span class="myimages group-3" id="tag-17">lunch</span>
This is the relevant CSS:
.myimages {position: absolute;}
.group-1 {
left: 191px;
top: 217px;
background-color: pink;
}
...
And there's nothing left to do but to actually dinamically assign the classes.

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