So In javascript you can do things like
document.querySelector('html').style.filter = 'invert(100%)'
Which Inverts colors on the entire webpage
but is there anyway to use
document.querySelector('html').style.pointer = 'something'
or a way to
add a css rule or something to the document?
example
you have an element like this
hello
then js gives an class
hello
then js adds a css rule?
.why {}
You could write to the document using document.write
document.write(`
<style>
#text {
color: red;
}
</style>`)
<h1 id='text'>Hello</h1>
Or, you can also create an element and append it to the document
let style = document.createElement('style')
style.innerHTML = `
.text {
color: red;
}
`
document.body.appendChild(style)
<h1 class='text'>Hello</h1>
You can add a css class to specific element with (and then create the styles from the css file):
[NameOfTheElement].classList.add("mystyle")
This will work for the document:
document.querySelector('html').classList.add('new-class');
This will work for the body:
document.querySelector('body').classList.add('new-body-class')
There are a few ways.
If you already have styles defined for a certain class within your stylesheet, you can do what Erasmo said above:
element.classList.add('className');
You can also use:
element.style.color = 'white';
Or add a style attribute to the element:
element.setAttribute('style', 'color: white; background-color: green;');
Related
I want to style element in javascript easily but this function doesn't work
const addStyles = function (el, styles) {
Object.assign(el.style, styles);
}
You need to get the element first, then access the style property (it's a string) and set your CSS there.
Here's an example. As you can see the text is black and there is no CSS, however, with the javascript line I can make it red.
function addStyles(element, style) {
element.style = style;
}
const myElement = document.getElementById("myText");
addStyles(myElement, "color: red; font-size: 25px;");
<p id="myText">Some text<p>
I need to be able to change out the css applied to the <body> on the fly. How, using javascript, could this be accomplished?
My css is stored as a string in a Javascript variable. I am not working with css files. The css consists of around 50 classes, so it doesn't make sense to apply them one-by-one. I know how this could be accomplished by changing the lowest class, but I'm just trying to see if it's possible to do using Javascript commands and variables.
Pseudo Code
var x = "#nav-bar-wrapper {
background-color: #4a3e7d;
padding: 20px 0;
}
#header-nav {
display: flex;
justify-content: center;
}...";
function changeCss() {
var el = $('myelement');
SomeJavaScriptFunction(el, x);
}
As #evolutionbox pointed out, it looks like you want to add new styles to the page. If so, just add them as text content in a style element:
const css = '#nav-bar-wrapper { ... }'
function changeCss() {
const el = document.createElement('style')
el.textContent = css
document.head.appendChild(el)
}
One easy way of doing it would be:
document.querySelector("yourElement").style.cssText += "Your super long string will go here and itll work"
Although, I dont think theres a way of giving different elements a uniqe style all in one line other than appending a style tag to the html. To use the method above, you'd have to separate #nav-bar-wrapper and #header-nav
Just keep in mind to use `` rather than "" to make the string go onto multiple lines
Here's a more JavaScript-y method than using hacky style tags.
const button = document.getElementById('button');
button.onclick = () => {
[
[ 'background', 'black' ],
[ 'color', 'white' ]
].map(([ prop, val ]) => {
button.style[prop] = val;
});
};
<button id="button">Hello there</button>
You could also try out https://cssinjs.org, which also works great in React.
Perhaps using jQuery's .css() function is worthy too: https://api.jquery.com/css/. It can take an object of CSS properties and apply them to an element.
$('#button').on('click', () => {
$('#button').css({ background: 'black', color: 'white' });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="button">Hi there</button>
You could also create a new style tag and append it to the body as many people have said. You can even append an external link rel="stylesheet" tag to the header to dynamically add a stylesheet from another URL! An alternative to this would be using the fetch API/jQuery AJAX/xmlhttprequest plus the code below:
$('#button').on('click', () => {
$('body').append('<style>#button { background: black; color: white; }</style>');
});
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="button">Hi there</button>
</body>
Another approach is using classes that you can dynamically add in JavaScript.
$('button').on('click', () => $('#button').addClass('clicked'));
.clicked {
background: black;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="button">Hi there</button>
You need to get a reference of your html element and after manipulate the DOM, here is an example:
document.getElementById('yourElementIdHere').style.color = 'red';
If you want to get your body reference to manipulate the DOM, you can do it. After this, you can change the style of your body using the style property, and use your string with your css.
document.querySelector("body").style = yourCssStringVar;
This link can help you, too:
JavaScript HTML DOM - Changing CSS
I've got a chunk of CSS as a string, and I want to insert it into the DOM such that it only applies to elements in a particular container. Some tools, like Polymer, for example, rewrite CSS selectors so they only apply within a limited scope. How can I do something similar so that, when I insert this CSS into the DOM, it won't change all elements on the page?
To make it more concrete, imagine the following HTML and CSS from an external source:
<style>p { font-size: 20px; }</style>
<p>Boo.</p>
I want to insert these elements into a #container element, but I don't want to change the font-size for all <p> elements. I'd like to rewrite all the selectors inside that <style> element so they only apply within #container (p -> #container p, etc.). How?
Use https://github.com/reworkcss/css to parse the CSS, then alter selectors, and finally stringify:
const CSS = require('css');
function scopeCSS(css, scope) {
const ast = CSS.parse(css);
for (let rule of ast.stylesheet.rules) {
if (rule.type == 'rule') {
rule.selectors = rule.selectors.map(selector => `${scope} ${selector}`);
}
}
return CSS.stringify(ast);
}
scopeCSS('div { color: black; }', '#foo');
// #foo div {
// color: black;
// }
http://requirebin.com/?gist=trevordixon/839d0674531dafa98fb95ae51474245e
For example: i have <div class="oneClass twoClass colorRed">Content</div> and i want to find the color* class and replace the color part "Red" with the new value "Blue" or "Yellow" for example so it would be "colorBlue" now...
How do i do that with Javascript only ?
Thanks!
Update:
This isn't my question: Change an element's class with JavaScript
var node = document.getElementById('someDiv');
node.className = node.className.replace(/color.*/, 'colorBlue');
/* This css snippet will allow to see
* element's classes rendered with the html ;)*/
div:after {
content: attr(class);
margin-left: 5px;
font-style: italic;
color: gray;
}
<div id="someDiv" class="oneClass twoClass colorRed">Content</div>
Select the div tag.
Get the element.className of the div tag so you have the classnames as a string.
Use a regular expression to replace the colorRed part of the string with colorBlue.
use .className again to set the class of the div to your editted string.
If you don't have to support IE, you can use element.classList and its methods.
So i just ran into this problem. Let's say I have the following markup:
<article data-color='#123456'>
<header>...</header>
<a href='#'>Lorem ipsum</a>...
...
</article>
So I have an element with a custom color attribute. I want to have the header have it as a background color, and the link as a color (the color is either randomly generated or user-defined). Is there a way to do this is CSS alone? (I am aware that jQuery would do this without a problem, but I'd like to kepp things as pretty as possible, not using Javascript for styling alone.)
You can use an attribute selector in your CSS:
article[data-color="#123456"] header {
background-color: "#123456";
}
article[data-color="#123456"] a {
color: "#123456";
}
However, this assumes you can enumerate the data-color attributes in your CSS. If it's generated dynamically and can take any value, you can't do it in CSS -- it doesn't have variables or back-references.
Unfortunately CSS cannot do this. the JS is relatively simple though:
$('article').filter(function() {
return $(this).data('color');
}).each(function() {
var $el = $(this), color = $el.data('color');
$el
.find('header').css('background-color', color).end()
.find('a').css('color', color);
});
Example fiddle
I think you can do it like this:
article[data-color="#123456"] header {
background-color: attr(data-color color);
}
article[data-color="#123456"] a {
color: attr(data-color color);
}
UPDATE
The first answer is incorrect, it doesn't work.
Do this rather:
article[data-color="#123456"] header {
background-color: "#123456";
}
article[data-color="#123456"] a {
color: "#123456";
}