How to add Tailwind styles in js dynamically? - javascript

There's a block:
let block = document.createElement('div')
how to add styles without creating css file? I mean we can do the following:
block.classList.add('classname')
but in this way we must create css file with classname we use
I want to add styles right in js, something like this:
block.addTailwindStyles('w-full')
I try to write the following way but all of them doesn't work:
el.classList.add('w-full')
el.className = 'w-full'
el.style.cssText = 'w-full'

First option now is working...
el.classList.add('w-full')
to adding multiple styles write in double quotes:
el.classList.add("w-full", "text-bold", ...)

Related

Adding a class (related to tailwind) using javascript doens't work

I have a button with a PLUS svg image in it. On click, I what that Plus svg to disappear. I checked in console and the function works fine, the class "visible" is removed and the class "invisible" is added. But in the UI the Plus svg doesn't disappear.
"Invisible" is a class in Tailwind that should make an item to be hidden.
const BtnAddEle = document.querySelector(".addEle");
const plusSvg = document.querySelector(".addElePlus");
BtnAddEle.addEventListener("click", function () {
plusSvg.classList.remove("visible");
plusSvg.classList.add("invisible");
});
This is happening because tailwind only adds class styles which you have used in the final CSS file
So you can do something like this
const BtnAddEle = document.querySelector(".addEle");
const plusSvg = document.querySelector(".addElePlus");
BtnAddEle.addEventListener("click", function () {
plusSvg.style.visibility = "hidden"
});
The reason why it is not working for you is that-
To have tailwind classes to work from JS file you have to define the path of js file in the content portion of tailwind.config.js file.
Example:
content: ["./*.{html,js}", "./src/**/*.{html,js}"]
Using this, your tailwind compiler will know that you are trying to add a css class from your JS file and that class will appear in the output css file.
Content Configuration is mentioned and explained in details - Here [Official Documentation]

Will adding an id to a html style tag cause issues?

I have a javascript application where for some obscure reasons I need to:
Inject styles into my html head
Remove these styles from my html head at a later stage
My simplified setup I have right now is something like this...
Injecting the <style ...> tag:
const css = `
* {
outline: 2px dashed lime;
}
`;
const styleEl = document.createElement('style');
styleEl.id = 'myid';
document.head.appendChild(styleEl);
styleEl.appendChild(document.createTextNode(css));
And at another time I want to remove those styles again, using the id I assigned to identify the <style ...> tag, because a lot of other style nodes are in the head:
const styleElement = document.getElementById('myid');
if (styleElement && styleElement.parentNode) styleElement.parentNode.removeChild(styleElement);
I think the id on the <style ...> tag is not valid HTML. But can also not think of another elegant way of solving this. I cannot use inline styles in this case, because the styles should apply the whole document (actually targeting an injected iframe).
Thoughts and help is much appreciated!
You don't have to get it by id again. You have it in styleEl variable, so just remove it from a DOM like this:
styleEl.remove(); // remove it from the DOM
You can do this repeatedly. Append and remove.

How to change a background that is declared in .css not html

USING JAVASCRIPT, NO JQUERY
Hi all,
I know this is a basic one but I am hitting a dead end.
I want to change a background image that is in the .css, not the html so I cant give it an id. I managed to remove the image using:
var headerImg = document.getElementById('header').background = 'none';
And tried :
var headerImg = document.getElementById('header').background = 'images/new-header.jpg;
But that did'nt work.
I have no idea how to change the Image, and in the dev tools the url does not even change when I try to run my code Any help would be great, Thanks.
You're close. You're just off on the syntax slightly...
document.getElementById("header").style.backgroundImage = "url(images/new-header.jpg)";
It's a style attribute you're changing, so you need .style and then you use the CSS attribute name, but remove hyphens and camelCase the attribute name, so .backgroundImage.
Can you try this
var element = document.getElementById('content');
element.style.backgroundImage = "url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSzOpUTzDIq2yutn75PQTLcHhJ06MTZPsV_V-0M918xKUhAqMxE')";
<div>
<p>this is unchanged</p>
<p id="content">backgroud wiil be cange</p>
<div>

Using JS, is it possible to return a list of all CSS stylesheets included in a page, when it loads?

Using jQuery or plain JavaScript, can I return a list of every stylesheet included in a page when it initially loads?
All I want to do is print out a list of stylesheet names into the console, no additional info on the stylesheets is required.
If I am correct, by Names you mean the file name of each stylesheet.
Consider this example:
jQuery("link[href*='.css']").each(function(){
console.log(jQuery(this).attr('href').split('/').pop());
});
Here I am using this link[href*='.css'] selector to select all (include the inactive) stylesheets.
if using jQuery:
console.log($('link[rel=stylesheet]'));
If you're using jQuery, you could do something along the lines of:
$(document).ready(function() {
console.log($("link[rel='stylesheet']").attr("href"));
});
https://jsfiddle.net/vzfhjg16/
This piece of code collects all links with the rel attribute on stylesheet, then iterates over them and logs their attribute href. You can use the line in the loop to display the stylesheet names anywhere you want to.
$("head link[rel='stylesheet']").each(function (){
console.log($(this).attr("href"));
});
Working example
try this,
var styles = document.styleSheets;
$(styles).each(function(index,value){
console.log(value.href==null ? null : value.href.split('/').pop())
});
var styleSheetList = document.styleSheets;
ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets

I'm unable to inject a style with an "!important" rule [duplicate]

This question already has answers here:
Overriding !important style
(11 answers)
Closed 1 year ago.
I tried to inject a style using this code:
document.body.style.color='green!important';
Per the CSS cascade ref, by applying the !important rule I can trump origin and specificity.
I tried to inject this using Firefox Firebug into www.google.com however no luck.
How do I inject a foreground color with an !important rule?
Per the spec, if you want to set the priority, not just the value, you have to use setProperty, like so:
document.body.style.setProperty ("color", "green", "important");
element.style.cssText = 'color:green !important';
should work for you.
style.cssText is the only way to add !important.
<script>
document.body.style.cssText='color: red !important;'
</script>
all answers are great but they all assumed the value of the attribute is fixed,, what if not
take look at my solution
this.style.setProperty("color", $(this).css('color'), "important");
instead of hand writing the value, I got it using jquery $(this).css('attr')
I would like to pose that it may not be working not so much due to any error in code (excepting the space) but more because modifying the body tag isn't a specific enough element, class, or what have you to create the desired effect.
Like for instance the page text of a search result has a class of "st".
all search results are each encapsulated in an
<li>
tag.
So some code to such effect might look like this:
var arr = document.getElementsByClassName('st');
for(i=0; i<arr.length; i++){
arr[i].style.color="green";
}
Use only this:
document.body.style.color="green";
you can not have to use important in this way. Anyway as Fatal pointed out, this will not work, when there is directly important rule in css stylesheet, that you need to override.
In that way, you have to dynamicaly create stylesheet and ad it inside head:
function addNewStyle(newStyle) {
var styleElement = document.getElementById('styles_js');
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = 'styles_js';
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
styleElement.appendChild(document.createTextNode(newStyle));
}
Then you can update style just like that
addNewStyle('body {color:green !important;}')
i need to keep !important for the following code how to do
<script> var size = $(window).width();
if(size >="1900" && size <="2890"){
$(document).ready(function(){ $(".myMove").click(function(){ $(".hqnblogo").animate({ left:'-22% ', top: '67%', height:'7%', }); $(".hqnbnaturalslogo").animate({ left: '86%', top: '20px', height:'7%', }); }); }); } </script>?

Categories