How can I get the css file text via javascript? - 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)
}

Related

Add a StyleSheet in JS and allow it to be toggled dynamically

I know how to use JS to add a stylesheet to an HTML document:
// given CSS as text, add a <style> to the document
function addStyle(css) {
var style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
}
How do I create a checkbox that can toggle this (and only this) stylesheet on and off?
This answer gives hints about how to manipulate stylesheets in JS, but there does not appear to be a way of locating a specific stylesheet without looping through document.styleSheets and matching against document.styleSheets[i].cssRules[j].cssText, which seems unwieldy.
Is there a better way to do this, ideally without jQuery, than a double loop?
(My particular use case is for a userscript (e.g. Greasemonkey), though I avoid GM_addStyle for portability. All this really means is that I don't have direct control over the HTML; I'm modifying other sites.)
In writing this question, I figured out the answer, though it still leaves open the question of how to manipulate preexisting stylesheets without too many loops.
Basically, while I can't use getElementById() or querySelector() to find a style element by its id attribute (because it's not in the body), I can save the object itself when I create it:
// given CSS as text, add a <style> to the document and return it
function addStyle(css) {
var style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
return style;
}
var toggler = addStyle(`
tr.informational { display:none; }
`);
// create and insert the toggling checkbox
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = true;
checkbox.onchange = function() { toggler.disabled = ! toggler.disabled };
var label = document.createElement("label"); // <label> allows clicking on text
label.appendChild(checkbox);
label.appendChild(document.createTextNode("Hide informational rows"));
document.getElementById("buttons").appendChild(label); // add to button panel
I had previously thought that Greasemonkey's security prevented accessing its objects after it finishes loading. This would have meant the checkbox.onchange() line wouldn't work. My original code was therefore quite ugly, finding toggler_index by looping over document.styleSheets[] to find my CSS and then constructing independent JS within JS by hard-coding that index:
checkbox.setAttribute("onchange", `
var toggler = document.styleSheets[${toggler_index}];
toggler.disabled = ! toggler.disabled;
`);
Thanks to StackOverflow for forcing me to question my assumptions when simplifying my question for posting here!

Cross-browser dynamic setting of a CSS property

I have a function that gets many pieces of data and sets a CSS property for a defined element.
Here is the code:
function setStyle(element,property,target){
element.style[property] = target;
}
var EL = document.getElementById("id");
setStyle(EL,"width","50px");
It works well in most browsers but not for IE6–IE9.
I've found document.defaultView.getComputedStyle and element.currentStyle[type], but these methods get style and I can't use them to set.
Is there any way to do that for old IEs?
i don't want to use jQuery or any other JS library, thanks.
The default way would be element.style.property = "value", like:
document.getElementById("id").style.width = "50px";
There's no reason why it shouldn't work. But, as an alternative, consider setting the css style in a class, and adding it to the element by the className property.. It is widely supported:
css:
.myClass { width: 50px; }
js:
document.getElementById("id").className = "myClass";
EDIT
Yet another way around, that works in IE8+ (If you don't really need anything lower) would be setting the actual style atribute to the DOM element, so you can get the property as a parameter:
http://jsfiddle.net/ppf5qcvo/
function setStyle(element,property,target){
element.setAttribute("style", property + ":" + target);
}
var el = document.getElementById("test");
setStyle(el, "color", "red");
Have you considered using jQuery? It handles all the cross browser issues for you. You could accomplish the same thing with the following statement:
$('#id').width('50px');

Customization of css attributes

I'm trying to customize the color attribute of this element this way:
<h2 style="float:left;font-family:'Open Sans',sans-serif;color:#fbfbfb;font-size:40px;position:relative;margin-top:-458px;margin-left:90px;" class="main-title">TEST</h2>
js code (included in the top of the html page)
(function(){
document.getElementsByClassName('main-title').color = 'black';
})();
Doing this wouldn't change the color. Including it at the bottom of the page involves the same issue. Also, I've tried to include a css file which contains(.main-title{color:black;}) instead of that js file, but it still the same. How to fix this, please?
Any brilliant idea ?
There should be
document.getElementsByClassName('main-title')[0].style.color = 'black';
Because getElementsByClassName returns a collection not a single element. And color is a key in style property.
You have Top-margin = -458px so that element will never appear. So may be you are not able to view that element itself.
You need to update the style property of the element
document.getElementsByClassName('main-title')[0].style.color = 'black';
You can also update all the elements with this classname with the following
var els = document.getElementsByClassName('main-title');
for (var i = 0; i < els.length; i++){
els[0].style.color = 'black'
}

Remove hashtags with Javascript

Is there a way to hide all hashtags on the page with javascript?
For instance, I have a tag cloud underneath each post on a website I'm making. Each tag looks something like: #myhashtag
I want javascript (possibly css?) to run through the document and hide the "#" so that the tag ends up simply looking like: myhashtag
is this possible?
Let the hash tags be elements with a specific class. (Just edit the CSS selector accordingly if you have other identification marks.) Than 8 lines jQuery should do the trick:
$('.my-hash-tag').each(function(i, elem) {
var $elem = $(elem), text = $elem.text();
if(text.length > 0 && text.charAt(0) == '#') {
$elem.text(text.substring(1));
}
});
This will do the job, comments explain how it works. Currently it assumes the tags are inside anchors and inside a div with id #cloud however this is easily edited, just use a different element selector the concept remains the same.
var tagCloud = document.getElementById("cloud"); // Get tag cloud element
var tags = tagCloud.getElementsByTagName('a'); // Find all anchors within cloud (If they aren't anchors change this to containing elements or replace with a class search .etc
for (var i=0, max=tags.length; i < max; i++) { // Loop through tags
tags[i].innerHTML = tags[i].innerHTML.replace("#", ""); // Remove #'s
}
Working fiddle: http://jsfiddle.net/3ayhA/1/
var doc = document.body;
doc.innerHTML = doc.innerHTML.replace(/(\B)#(\w+)\b/g, '$2');

How to get all css's settings using jquery?

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
....

Categories