How put style in a element javascript [duplicate] - javascript

How I can set a style of a:visited with JavaScript or jQuery. I know how to set with a regular link like
document.getElementById('a12').style.color = '#ff0000';
But I don't know how it works with a:visited?

Style properties adjust style attributes which apply to elements, they completely replace selectors
You have two choices.
Write your rule-sets in advance, and then design the element to match the selector.
e.g.
.foo:visited {
color: #f00;
}
document.getElementById('a12').className += ' foo';
Dynamically generate rule-sets with selectors that match the element.
See bobince's answer at Setting CSS pseudo-class rules from JavaScript

Related

Set Property Value of Pseudo-Elements Using 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)
How to update placeholder color using Javascript?
(5 answers)
Closed 2 years ago.
Is it possible to change a CSS pseudo-element style via JavaScript?
For example, I want to dynamically set the color of the scrollbar like so:
document.querySelector("#editor::-webkit-scrollbar-thumb:vertical").style.background = localStorage.getItem("Color");
and I also want to be able to tell the scrollbar to hide like so:
document.querySelector("#editor::-webkit-scrollbar").style.visibility = "hidden";
Both of these scripts, however, return:
Uncaught TypeError: Cannot read property 'style' of null
Is there some other way of going about this?
Cross-browser interoperability is not important, I just need it to work in webkit browsers.
If you're comfortable with some graceful degradation in older browsers you can use CSS Vars. Definitely the easiest of the methods I've seen here and elsewhere.
So in your CSS you can write:
#editor {
--scrollbar-background: #ccc;
}
#editor::-webkit-scrollbar-thumb:vertical {
/* Fallback */
background-color: #ccc;
/* Dynamic value */
background-color: var(--scrollbar-background);
}
Then in your JS you can manipulate that value on the #editor element:
document.getElementById("#editor").style.setProperty('--scrollbar-background', localStorage.getItem("Color"));
Lots of other examples of manipulating CSS vars with JS here: https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/
To edit an existing one which you don't have a direct reference to requires iterating all style sheets on the page and then iterating all rules in each and then string matching the selector.
Here's a reference to a method I posted for adding new CSS for pseudo-elements, the easy version where you're setting from js
Javascript set CSS :after styles
var addRule = (function (style) {
var sheet = document.head.appendChild(style).sheet;
return function (selector, css) {
var propText = typeof css === "string" ? css : Object.keys(css).map(function (p) {
return p + ":" + (p === "content" ? "'" + css[p] + "'" : css[p]);
}).join(";");
sheet.insertRule(selector + "{" + propText + "}", sheet.cssRules.length);
};
})(document.createElement("style"));
addRule("p:before", {
display: "block",
width: "100px",
height: "100px",
background: "red",
"border-radius": "50%",
content: "''"
});
sheet.insertRule returns the index of the new rule which you can use to get a reference to it for it which can be used later to edit it.
EDIT: There is technically a way of directly changing CSS pseudo-element styles via JavaScript, as this answer describes, but the method provided here is preferable.
The closest to changing the style of a pseudo-element in JavaScript is adding and removing classes, then using the pseudo-element with those classes. An example to hide the scrollbar:
CSS
.hidden-scrollbar::-webkit-scrollbar {
visibility: hidden;
}
JavaScript
document.getElementById("editor").classList.add('hidden-scrollbar');
To later remove the same class, you could use:
document.getElementById("editor").classList.remove('hidden-scrollbar');
I changed the background of the ::selection pseudo-element by using CSS custom properties doing the following:
/*CSS Part*/
:root {
--selection-background: #000000;
}
#editor::selection {
background: var(--selection-background);
}
//JavaScript Part
document.documentElement.style.setProperty("--selection-background", "#A4CDFF");
You can't apply styles to psuedo-elements in JavaScript.
You can, however, append a <style> tag to the head of your document (or have a placeholding <style id='mystyles'> and change its content), which adjusts the styles. (This would work better than loading in another stylesheet, because embedded <style> tags have higher precedence than <link>'d ones, making sure you don't get cascading problems.
Alternatively, you could use different class names and have them defined with different psuedo-element styles in the original stylesheet.
I posted a question similar to, but not completely like, this question.
I found a way to retrieve and change styles for pseudo elements and asked what people thought of the method.
My question is at Retrieving or changing css rules for pseudo elements
Basically, you can get a style via a statement such as:
document.styleSheets[0].cssRules[0].style.backgroundColor
And change one with:
document.styleSheets[0].cssRules[0].style.backgroundColor = newColor;
You, of course, have to change the stylesheet and cssRules index. Read my question and the comments it drew.
I've found this works for pseudo elements as well as "regular" element/styles.
An old question, but one I came across when try to dynamically change the colour of the content of an element's :before selector.
The simplest solution I can think of is to use CSS variables, a solution not applicable when the question was asked:
"#editor::-webkit-scrollbar-thumb:vertical {
background: --editorScrollbarClr
}
Change the value in JavaScript:
document.body.style.setProperty(
'--editorScrollbarClr',
localStorage.getItem("Color")
);
The same can be done for other properties.
Looks like querySelector won't work with pseudo-classes/pseudo-elements, at least not those. The only thing I can think of is to dynamically add a stylesheet (or change an existing one) to do what you need.
Lots of good examples here:
How do I load css rules dynamically in Webkit (Safari/Chrome)?

access a set of seclectors with :before using 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)
How to update placeholder color using Javascript?
(5 answers)
Closed 2 years ago.
Is it possible to change a CSS pseudo-element style via JavaScript?
For example, I want to dynamically set the color of the scrollbar like so:
document.querySelector("#editor::-webkit-scrollbar-thumb:vertical").style.background = localStorage.getItem("Color");
and I also want to be able to tell the scrollbar to hide like so:
document.querySelector("#editor::-webkit-scrollbar").style.visibility = "hidden";
Both of these scripts, however, return:
Uncaught TypeError: Cannot read property 'style' of null
Is there some other way of going about this?
Cross-browser interoperability is not important, I just need it to work in webkit browsers.
If you're comfortable with some graceful degradation in older browsers you can use CSS Vars. Definitely the easiest of the methods I've seen here and elsewhere.
So in your CSS you can write:
#editor {
--scrollbar-background: #ccc;
}
#editor::-webkit-scrollbar-thumb:vertical {
/* Fallback */
background-color: #ccc;
/* Dynamic value */
background-color: var(--scrollbar-background);
}
Then in your JS you can manipulate that value on the #editor element:
document.getElementById("#editor").style.setProperty('--scrollbar-background', localStorage.getItem("Color"));
Lots of other examples of manipulating CSS vars with JS here: https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/
To edit an existing one which you don't have a direct reference to requires iterating all style sheets on the page and then iterating all rules in each and then string matching the selector.
Here's a reference to a method I posted for adding new CSS for pseudo-elements, the easy version where you're setting from js
Javascript set CSS :after styles
var addRule = (function (style) {
var sheet = document.head.appendChild(style).sheet;
return function (selector, css) {
var propText = typeof css === "string" ? css : Object.keys(css).map(function (p) {
return p + ":" + (p === "content" ? "'" + css[p] + "'" : css[p]);
}).join(";");
sheet.insertRule(selector + "{" + propText + "}", sheet.cssRules.length);
};
})(document.createElement("style"));
addRule("p:before", {
display: "block",
width: "100px",
height: "100px",
background: "red",
"border-radius": "50%",
content: "''"
});
sheet.insertRule returns the index of the new rule which you can use to get a reference to it for it which can be used later to edit it.
EDIT: There is technically a way of directly changing CSS pseudo-element styles via JavaScript, as this answer describes, but the method provided here is preferable.
The closest to changing the style of a pseudo-element in JavaScript is adding and removing classes, then using the pseudo-element with those classes. An example to hide the scrollbar:
CSS
.hidden-scrollbar::-webkit-scrollbar {
visibility: hidden;
}
JavaScript
document.getElementById("editor").classList.add('hidden-scrollbar');
To later remove the same class, you could use:
document.getElementById("editor").classList.remove('hidden-scrollbar');
I changed the background of the ::selection pseudo-element by using CSS custom properties doing the following:
/*CSS Part*/
:root {
--selection-background: #000000;
}
#editor::selection {
background: var(--selection-background);
}
//JavaScript Part
document.documentElement.style.setProperty("--selection-background", "#A4CDFF");
You can't apply styles to psuedo-elements in JavaScript.
You can, however, append a <style> tag to the head of your document (or have a placeholding <style id='mystyles'> and change its content), which adjusts the styles. (This would work better than loading in another stylesheet, because embedded <style> tags have higher precedence than <link>'d ones, making sure you don't get cascading problems.
Alternatively, you could use different class names and have them defined with different psuedo-element styles in the original stylesheet.
I posted a question similar to, but not completely like, this question.
I found a way to retrieve and change styles for pseudo elements and asked what people thought of the method.
My question is at Retrieving or changing css rules for pseudo elements
Basically, you can get a style via a statement such as:
document.styleSheets[0].cssRules[0].style.backgroundColor
And change one with:
document.styleSheets[0].cssRules[0].style.backgroundColor = newColor;
You, of course, have to change the stylesheet and cssRules index. Read my question and the comments it drew.
I've found this works for pseudo elements as well as "regular" element/styles.
An old question, but one I came across when try to dynamically change the colour of the content of an element's :before selector.
The simplest solution I can think of is to use CSS variables, a solution not applicable when the question was asked:
"#editor::-webkit-scrollbar-thumb:vertical {
background: --editorScrollbarClr
}
Change the value in JavaScript:
document.body.style.setProperty(
'--editorScrollbarClr',
localStorage.getItem("Color")
);
The same can be done for other properties.
Looks like querySelector won't work with pseudo-classes/pseudo-elements, at least not those. The only thing I can think of is to dynamically add a stylesheet (or change an existing one) to do what you need.
Lots of good examples here:
How do I load css rules dynamically in Webkit (Safari/Chrome)?

Can we Create CSS Selector rule with JQuery or Javascript?

we can create style or any other tag with
var st = document.createElement("style");
and even append the same to body
body.append(st);
and it will create
<body><style></style></body>
I wanna know can we put style in style tag with javascript as well not simple rules, I know there is $("selector").css() function is there which can apply css rules to selector but i want a bit more powerful rule and I want to add in style tag i just created,
something like this:
<style>
div.bar {
text-align: center;
color: red;
}
</style>
st.innerHtml or st.innerText are not letting me set these values.
Note: This was asked me to do in Browser Console only.
You can simply use jquery .text method like
const cssCode = `div.bar {
text-align: center;
color: red;
}`
$('style-tag-selector').text(cssCode)
but in my opinion, whetever your goal is - this solution is not ok. You shouldn't mess with CSS via JavaScript.
Best approach is to have styles in separately loaded .css file and then you can toggle classes to elements with javascript.
You can add your css directly within the style tag and append them to the head of your page:
$( "head" ).append( "<style>div.bar {text-align: center; color: red}</style>" );
You can append multiple style tags with css in the head beneath each other, in this way you can override previous syles, but it is not best practice.
I prefer having your styles in separate files and to manage wether or not the files will be included in your code.
Actually there's an interface for this. For example, add a style element and add a rule to it (this will result in anything with the class should-be-red to be red.
var styleElement = document.createElement('style');
document.head.appendChild(styleElement);
var sheet = styleElement.sheet;
sheet.insertRule('.should-be-red { color: red; }', 0);
You can iterate over the rules and insert/delete rules and exciting things like that.
More info: https://developer.mozilla.org/en-US/docs/Web/API/CSSStylesheet
jsbin: https://jsbin.com/jodiro/1/edit?html,js,output

difference between css/javascript selectors

What is the difference between div#name and #name? Or is there a difference if you use class or id to position a certain element? Thank you
the first one is more specific if you have several rules applying
for instance, in this example the first case "wins", since it is more specific.
div#kuku {color:red}
#kuku {color:blue}
A good source for reading: http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
You use IDs for elements that appear once in the document. You use classes for more than one elements in the page.
What is the difference between
div#name and #name?
div#name
refers to only that div which has id 'name'
while #name refers to any element having id 'name'
Class selectors can apply to many tags, while an id is uniquely associated with a single tag. So I'd say that a class selector will return multiple elements, while an id selector would return one.
div#name limits the selector to DIVs with the id only.
#name apples to any element with that id.
As #naivists points out, in case of a concurrency between two rules the more explicit one (div#name) wins.
IDs are unique on a page and have more specificity. In other words, if you have
<div id="foo" class="bar">
Then
#foo{
background: green;
}
div#foo{
background: red;
}
.bar{
background: purple;
}
will be red. There is a good Specificity Wars explanation of this using Darth Vader and Star Wars here
http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
Image here:
http://www.stuffandnonsense.co.uk/archives/images/specificitywars-05v2.jpg
In brief an ID # trumps any number of classes (.) which in turn trump any number of tag selectors. e.g:
# *beats* . . . . *beats* body div div ol li p
div#name will match
<div id="name">foo</div>
but not
<span id="name">foo</span>
#name will match both, but you cannot have both in the same document as IDs are unique in the document, and classes can be multiple.
As for positioning, you generally have a number of elements with a given classname but id is specific to a single element. You generally do not want to position a number of elements at the same time, unless it is for only 1 axis.

What's the equivalent of IE's document.all in DOM?

I basically want to dynamically apply some style to all elements in a page, I know document.all is proprietary to IE, so, what's the equvalent (if any) in DOM? Is there an equivalent to * in css in DOM?
Note: Don't want to use JQuery or any other JS lib for this, just JS, thanks
use document.getElementsByTagName('*')
The World Wide Web Consortium gives a clear specification of this method (Search for getElementsByTagName).
As Scharrels said, you can use document.getElementsByTagName('*'). But you should note that applying styles to every single element on a page is going to impact performance. It would be better to dynamically create a <style> tag and add the styles in there:
function addStyles(styles) {
var styleTag = document.createElement('style');
styleTag.type = 'text/css';
try {
styleTag.appendChild(document.createTextNode(styles));
} catch(e) {
/* Exception thrown in IE */
styleTag.stylesheet.cssText = styles;
}
document.getElementsByTagName('head')[0].appendChild(styleTag);
return styleTag;
}
Usage:
addStyles('* { color: red; }');
Yep, I have just tested documentAll document.getElementsByTagName("*") on Safari, Explorer6, Opera and Firefox and seems to work for all them :)
Applying a style to all elements is not something that you would normally do, so what is it that you are going to use it for?
There are some styles that you can't apply to all elements. A select element for example doesn't support setting borders in all browsers. Setting margin on inline elements can have varying unexpected results...
Some styles are inherited, so if you for example apply a font-size to the body element, that would be inherited by any elements that doesn't already have a specific font-size set.
You can use the cascading in CSS to change the style on a lot of elements. If you for example have this style defined:
.highlight div.info { background: #ffc; }
.highlight strong { color: #f00; }
Setting className="highlight" to the body tag would give every div inside with class="info" a light yellow background and every strong element red text.

Categories