How to get all css's settings using jquery? - javascript

I'd like to know all css settings in page using jquery. I know to get some css's setting, we do like this,
$('#container').css("width")
As this, I tried to use $('*') to get all css settings but couldn't success.
Please give me some advice.

If you want the elements with inline CSS try:
$("[style]").each(function() {
for (var i=0; i<this.style.length; i++) {
console.log(this.style[i] + " = " + this.style.getPropertyValue(this.style[i]));
}
});
Note: this uses the Javascript style names which are as per the CSS spec rather than those used in jQuery's css() (eg "margin-top" in CSS, "marginTop" in css()).
If you want all the style that's applied to an element based on its inline style and CSS rules defined both internally on the Web page and through external style sheets, that's going to be somewhat more difficult.
You can at least find the global style sheets with something like:
for (var i=0; i<document.styleSheets.length; i++) {
var css = document.styleSheets[i];
for (var j=0; j<css.length; j++) {
console.log(css[j] + " = " + css.getPropertyValue(css[j]));
}
}

For me your question isn't clear enough to answer. What is it exactly that you want to achieve?
all css settings in page
could mean a lot of different things.
Do you want the calculated CSS properties of the browser
Do you want the original CSS classes which apply (not the calculated values but the declared values from .css files) + all of them or only the most specific match
Do you want the original inline CSS stylings
Do you want a list of all included stylesheets
Do you really want all properties or only a selection thereof
Do you want this for every element on the page or only for specific ones
....

Related

Proper way to author Jquery plugins with style rules

I have been long battling this, and I would like to know if any others have feedback. I am about to make a customized library for building web apps quickly, and I want to make sure I use the right approach. I WANT to use this method:
$.fn.someSlider = function(){
var coreStyle = '.slider ul { white-space: nowrap; } .slider ul li {display: inline-block}', coreStyleTemplate = '<style><\/style>';
}
But I feel like hard coding the base CSS into the widget is always frowned upon - instead I see SO users recommending the use of CSS style rules instead of this option. I really really really want that 'it just works' feel, and having to force my users to use a separate style sheet just to get my plugins working... well is annoying!
Just to clarify: I would like to include all base style rules needed for the widgets proper/base functionality to be included inside the script. The user would easily modify the base look of the widget by writing a style rule in their own style sheet.
Example:
Instead of having to look through all the base styles trying to find the font color like this... .slider {display: inline-block; color: #000; someotherconfusingrule : blahblah; }
The user simply starts a new rule with the classes name/selector being used - and then just write the changes to make to the default script styles
They would just write
.slider {color: #000};
Thanks for the help in advance SO!
Nice question! Although I'm not sure what the preferred solution to this would be, I was thinking of the following approach:
Use a IIFE to define your jQuery plugin and enable you to define some private, global variables and functions.
$.fn.pluginName = (function() {
return function() {
...your regular plugins code...
};
}();
Define your plugins CSS as a list of style rules in your plugins code
var rules = [
'.box {' +
' width: 100px;' +
' background-color: #f99;' +
' margin: 10px;' +
' padding: 10px;' +
' font-family: Helvetica, Arial;' +
' text-align: center;' +
'}'
];
Create a private variable that remembers if your stylesheet has already been added to the document
var styleSheetExists = false;
Create a private function that creates a stylesheet using the style rules above and that adds it as the first <style> element in the <head> allowing the user to override styles in their own CSS. See http://davidwalsh.name/add-rules-stylesheets for a good tutorial on how to do this properly
var createStyleSheet = function() {
var style = document.createElement("style");
style.appendChild(document.createTextNode(""));
$('head').prepend(style);
for (var i = 0; i < rules.length; i++) {
style.sheet.insertRule(rules[i], i);
}
};
The first time your plugin is applied to an element check if the stylesheet has already been created and if not create the stylesheet.
var $elements = $(this);
if (!styleSheetExists) {
createStyleSheet();
styleSheetExists = true;
}
$elements.each(function() {
$(this).addClass('box');
});
return $elements;
See http://codepen.io/ckuijjer/pen/FkgsJ for this example. It creates a jQuery plugin called box which simply adds the class box to an element. The class box has a default pink background color defined in its stylesheet which gets overridden by a user defined blue background color.
But please do make this configurable in your jQuery plugin. You want to enable developers to bundle all their css, including your plugins, to optimize resource delivery to the client. Plus injecting stylesheets might be a small performance hit.
It may seem annoying but separating the model, view, and controller is the correct way. You're using jQuery so why not consider how jQuery would approach the situation: a jQuery UI widget like the Accordion comes with several stylesheets, the most important being the base stylesheet and a separate 'theme' stylesheet that (if done correctly) is nondestructive and can be modified without risking the integrity of the widget. You may also want to consider how your favorite plugins are authored and what makes them appeal to you. It's my personal opinion CSS should never be present in JavaScript files however if you've made up your mind, the solution #ckuijjer provided is sound. Hope this helps!

How can I get the css file text via javascript?

If I have a style tag on my page with css in it and I write the following javascript I will get the css text of all style tags.
//compatibility: all
$("style").each(function () {
alert($(this).text());
});
I want to get the same text from all link element css files, like the following script.
//compatibility: IE Only
$("link").each(function(){
alert(this.sheet.cssText);
});
Is there a cross modern browser friendly version of the above script?
Another way to access a CSS rule without actually accessing the stylesheet is to create an element, apply a rule to it and then access its properties with jQuery. Something like this:
var NewElement = $('.SomeClass');
var TheHeight = NewElement.prop('height');
Not sure if this would help but it's an idea. What are you trying to do anyway?
Edit:
var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules;
rules[0].style.color = 'red';
This is from the answer here I added a jsFiddle Note that you must select the correct stylesheet index.
The only possible solution is to use AJAX:
$("link").each(function(){
$.get(this.href, function(css){
alert(css);
});
});
Or you can use document.styleSheets
You can iterate over the style sheets:
var styleSheets = document.styleSheets;
for(var i = 0; i < styleSheets.length; i++){
alert(styleSheets[i].cssRules)
}

have element change appreance with only javascript and CSS

attempting to have my webpage be a bit more dynamic by having the background change on some elements when a checkbox is clicked. I am trying to do this via class change and a CSS sheet. I have the following which is kicking out an error that my onclick function ins not defined (in IE9). More importantly will the webpage update if I only change the class of the object which would have a different class in the CSS file. Whats a better alternative if this does not work?
my elemenet and function
UPDATE
I made updates to both my HTML and CSS file as suggested by many. I am still getting no change in my webpage but the console is claiming that my function called from the onclick event is not defined which is a bit odd since it is. Also does this type for scripting belong in the HTML or should I pull it out and put in a seperate file. I figured since it was creating elements it belongs in the main html. Is there a cleaner more compact way of accomplishing this and not making my home screen html huge?
<tr class= 'tr.notchosen'><td><input type='checkbox' onclick='handleClick(this.id)'/></td></tr>
function handleClick(cb) {
var currentColumn = cb.parentNode
var currentRow = currentColumn.parentNode
if (currentRow.className === "chosen")
{
currentRow.className = "notchosen";
}
else
{
currentRow.className = "chosen";
}
}
and my css file is the following
tr.chosen
{
background-color:rgba(255,223,0,0.75);
}
tr.notchosen
{
background-color:rgba(255,223,0,0);
}
There are a couple of things going on here. First, your css selector is not quite right. In fact, I would suggest making the class name just "chosen" or "not chosen" and then selecting tr elements with that class.
<tr class='notchosen'>
And then you can target it from css (which was probably the original intention)
tr.notchosen
{
background-color:rgba(255,223,0,0);
}
Further, although I would not suggest using inline javascript, using your example, you should pass this if you want to work with the element and not this.id which would pass a string.
onclick='handleClick(this)'
The last part would be to sync up your javascript with the class name change
if (currentRow.className == "chosen")
{
currentRow.className = "notchosen";
}
else
{
currentRow.className = "chosen";
}

Javascript: how to change the style of all links in a page?

I'm trying to change the style of all links in a page via Javascript.
I tried both these but no success:
document.links.style.cursor = "wait";
document.getElementsByTagName(a).style.cursor = "wait";
What am I doing wrong?
var allLinks = document.links || document.getElementsByTagName('a');
for(var n=0;n<allLinks ;n++)
document.allLinks [n].style.cursor = "wait";
The document.links is an array of elements, so document.links.style.cursor = "wait" equals to [link1,link2].links.style.cursor = "wait".
And about document.getElementsByTagName(a): the syntax is wrong, you forgot the quotes. The correct is document.getElementsByTagName("a")
var style = document.createElement("style");
document.head.appendChild(style);
try {
style.innerHTML = "a { cursor: wait; }";
}
catch (_ie) {
style.styleSheet.cssText = "a { cursor: wait; }";
}
Of course alternatively you could plan in advance for the eventuality of needing your links to change, and pre-load a static style sheet like this:
.wait-links a { cursor: wait; }
Then whenever you add the class "wait-links" to the <body> (or any container you like), the <a> tags will all be affected. That'd be much more efficient than iterating over the elements changing their individual styles (probably), though if there aren't many links it probably doesn't matter.
Using a style sheet for such things is, in my opinion, a much better practice. In this case, in fact, it'd be better not to call the class "wait-links", but rather use some word or words that describe what's actually happening. Then your JavaScript code just establishes the situation by adding (or removing) the class, and the style sheet controls the appearance changes. If you decide that in some cases the situation calls for the links to change color or become invisible, you can do that without having to root around in your scripts looking for style changes.
Using the JQuery and the ".css" method removes the need to have a for loop and simplifies the code.
$('a').css("cursor","wait");

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