Scenario
I have created a page where the client can build their own page, calendars, widgets, articles etc. I have created a second Dynamic builder page where they can build their own newsletters.
Problem
All my css is referenced with classes, because mailers are very limited I have to add all styles inline.
Question
Is there a script I can run to grab all referenced styles via class, and add it to the relevant elements/tags inline-styles?
Example [simple]
<p class='txtBlack'>Hello World</p>
Converts to
<p class='txtBlack' style='color:#000;'>Hello World</p>
Hope this is clear enough to understand.
I'd use element.currentStyle and window.getComputedStyle() for each element, then 'manually' read what I want and overwrite what I'm sure that doesn't work in mail apps.
I made example here: http://jsfiddle.net/Vmc7L/
Another way, is to read rules form style sheets and then apply them to inline style. But what if u got selectors like .myClass:firstChild>.anotherClass? :D Maybe jquery can help.
There're methods you need: http://www.quirksmode.org/dom/w3c_css.html
This so answer explains how:
Can I access the value of invalid/custom CSS properties from JavaScript?
CSSStyleDeclaration (https://developer.mozilla.org/en/DOM/CSSStyleDeclaration)
div {
width: 100px;
}
style:CSSStyleDeclaration object contains cssText:
cssText: "width: 100px"
CSSStyleDeclaration specification: http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration
To get all elements with class names use:
jQuery("[class]")
Here is the solution u can use the "getElementsByClassName" javascript function to collect the elements with the class names specified. But remember this doesnot work IE browsers. So for IE u have to have your own function. Hope this helps u.
Related
For some reason I can't access HTML element's display style's value.
Here's my JavaScript code:
var el = document.querySelector('#warning');
console.log(el.style.display)
My code returns "" empty string for #warning's displaystyle but it's actually "none".
I've the following HTML:
<div id="warning">
warning warning warning.
</div>
I've the following CSS:
#warning {
display: none;
}
Any ideas?
You are doing everything right for the most part, but what you are running into is a hangup for most people when they try this for the first time.
The style object in javascript is looking for this value to be inside the actual element (inline) and does not look for it in css code directly.
To access the style, the style has to exist in the dom. You could look into Window.getComputedStyle()
I hope this explains why you are reaching this roadblock.
If you know the element is an ID I'd suggest you use the getElementById(); function. Also AFAIK the style method gets inline styles only. I'd suggest using getComputedStyle();.
Code
var myDiv = document.getElementById("myDiv");
alert(getComputedStyle(myDiv).display);
Will output "none".
Example
http://jsfiddle.net/43jLLd5L/
Reading Material
Not directly related to your question but the answer has some good points.
I am able to easily change the style or the tag of an element based on certain criteria using JavaScript:
document.getElementsByTagName("mainclass")[0].style.color:#ffffff;
However, is there a way to do this is the style contains multiple classes and a tag like so
.mainclass .secondaryclass div td {
color: #000000;
}
The following is not working for me so im sure there is a totally different way of doing it:
document.getElementsByTagName(".mainclass .secondaryclass div td")[0].style.color:#ffffff;
...
The other option if easier is to figure out how to use JS to embbed a external style sheet (and not at the end of head, just where the JS code is thats where the CSS should go)
Thanks!
getElementsByTagName does not accept CSS selector syntax. You're looking for querySelectorAll but you'll have to iterate over the returned list to assign the style, and it's not completely supported across browsers.
...which is why everyone uses jQuery.
Example, assuming you want to modify just the first matched element:
document.querySelectorAll(".mainclass .secondaryclass div td")[0].style.color = '#ffffff';
Note the change from : to =, and wrapping the color value in quotes. JavaScript has different syntax from CSS; I suggest that you take some time to learn it.
My requirement is a bit tricky. I have a mark-up as below: (just an example, real mark-up is very complicated)
<div class="classA">
<div class="classB">
<p class="classC">
<span class="classD">
</span>
</p>
</div>
</div>
As you can see above, there are four CSS classes classA, classB, classC, classD associated with the markup.
Also I have used jQuery to bind events using these selectors.
My Requirement: I want the jQuery event binding to work and at the same time, the CSS should not get applied i.e. I want to negate the impact of CSS styles from a UI perspective, but from functional perspective jQuery event handlers should still work.
So, is it possible to override the CSS selectors such that their styles don't get applied to my mark-up elements ?
example below:
div.classA div.classB p.classC span.classD{
color:red;
}
I don't want the font color to be red, so I tried to override the selector as follows, but its not working:
div.classA div.classB p.classC span.classD{
color:red;
}
div.classA div.classB p.classC span.classD{
/*no styles here*/
}
Please help !!
Then just delete those classes from css. jQuery will still work though.
There is no requirement that only classes used in css have to be used in jquery.
For example:
<div class="someUnknownClass"></div>
Even though, there is no someUnknownClass defined in css, $('.someUnknownClass') will still work.
Use another class name for the selector. So you have classA for the css and classX for the selector.
If you don't want the styles applied. Then you could use $('selctor').css(); to over write the styles. Bit hacky!
OR.
Add a class that over-rides the css. Or remove the class that holds the css.
using: $('selctor').addClass('no_styles'); OR $('selctor').removeClass('current_styles');
I don't know any mechanism allowing to do that the way you want it.
the work around i would suggest would be binding your events on anoter css class and doing something like this :
$('.classD').addClass('eventClassD').removeClass('classD');
$('.eventClassD').on('myEvent', function(){...});
like this you will still have events binded to your elements and would get rid of all the css.
You want to do it without modifying the JS? There's no clean way to do that. But try this.
Presumably you will have something that distinguishes this special set of elements to distinguish it from other elements, of which styles' you want to retain. This is difference probably manifests itself in the form of a different parent container. Just copy the set of CSS rules that affect these classes, and prepend this parent CSS selector with the pre-class values.
"Basically, I do not want to touch the js code, and only if something can be done on the css front, then my requirement is achieved."
If that is all you need, then just remove all of the css definitions from the page.
$("link,style").remove()
In several jquery tutorials, separate ID and Class are used for JS and CSS. for example
<div id="test" class="test">TEST</div>
As ID is used in the jQuery code, and Class is used in CSS. To me it is easier to not introduce Class and use ID for CSS rule too. Is there any advantage to use css-less ID for javascript?
EDIT: Thanks folks! I know the difference between ID and Class; I am asking why some use separate ID and Class for JS and CSS when one is sufficient. Here, the matter is the necessity for uniqueness of ID. The case is separating JS and CSS tasks (while they are closely entangled).
EDIT2: As requested, I give a typical example: this Tutorial. Look for actionsBox; .actionsBox has been used for CSS and #actionsBox for JS. As you can see there is only one <div> so ID would be enough for styling.
Read “Don't use class names to find HTML elements with JS” for some reasons why you may want to avoid using classnames in JavaScript.
This all boils down to personal preference, really.
Edit: #Sharon commented a link to a great article that discusses the drawbacks of using id selectors in CSS.
One reason people might only use classes in CSS is the specificity of the id selector.
If you’ve got two style declarations for one element, and they specify different values for a property, then the style declaration with the more specific selector wins out.
For example:
HTML
<div id="test" class="special-test"></div>
CSS
#test {
color: red;
}
.special-test {
color: blue;
}
The ID selector trumps all other selectors for specificity (see http://www.w3.org/TR/selectors/#specificity for the rules), so here, the <div> will be red.
People who added class="test" to the <div> would presumably have written this:
HTML
<div id="test" class="test special-test"></div>
CSS
.test {
color: red;
}
.special-test {
color: blue;
}
When both style declarations have selectors with the same specificity, the later declaration wins out, so here the <div> would be blue.
Personally, I’ve never found that to be a problem. In the first example, all you have to write to make the <div> blue is this:
#test.special-test {
color: blue;
}
But I guess some people find this aspect of specificity unnecessarily complex, and so avoid it by only using class selectors in their CSS.
(And I assume they keep the id because it’s faster to retrieve a DOM element in JavaScript by id than by class.)
You can use both ID and Class with both javascript and css. For example:
CSS
/*ID as identifier*/
#some_id {
<css attributes>
}
/*Class as identifier*/
.some_class {
<css attributes>
}
Javascript:
/*Get by ID*/
document.getElementById("some_id");
/*Get by class*/
document.getElementsByClassName("some_class");
The difference between the two is that ID will, or at least should be, unique and therefore will only affect or return a single element when applying css rules or selecting via javascript respectively. Class on the other hand is for affecting or selecting elements of a similar nature or classification.
If you had a car park with ten cars in it and you were to say "I want the car in space number three" you'd expect a single return whereas were you to say "I want the Fords from the car park" you'd expect to return every car in the car park which was a Ford. Css and javascipt use of ID and Class is no different.
EDIT: As per the OP's new redefined line of questioning.
css and IDs:
Css can harness IDs as an anchor so that the contents of a uniquely identified DOM object. Consider the folowing piece of css.
#some_id tr:nth-child(odd) {
background-color:#666888;
}
In the above example the css is tied to a unique identifier which in this case the ID is assigned to a table but the css rules themselves are applied to the odd rows within the table. In other words the css in this case affects table row elements where TR itself is an object class (not to be confused with css class).
In short, for ID at least, it is useful to use IDs within css and when you consider that jQuery and the likes of support Class-based queries using Class for selection within javascript is also useful.
Curious about the dual nature of "ID" in javascript and CSS. If you visit this example from w3schools: http://www.w3schools.com/js/tryit.asp?filename=tryjs_blocks
you'll see the which is "naming" this particular <div> with the name "myDiv". This is because javascript getElementById("myDiv") is used later to modify the text contents of this specific <div>
BUT - if you add the line of code:
<style> #myDiv { color:blue; } </style>
you now have a CSS id with the same name as the javascript <div id>
The sample code in the w3schools does indeed change the color of the <div> called "myDiv" to blue. But when you push the "try it" button on that page, the CONTENTS of the javascript <div> also changes, which is the point of the w3schools example. Ie., it's teaching you that getElementById("myDiv") is how you can retrieve and modify contents of a named <div>
But because the identically named CSS #myDiv id is in force the <div> contents are changed, and they remain blue due to the style sheet.
So when you see a <div id="myDiv"> inside an HTML page, how can you readily tell if this <div> wants CSS id treatment? Or if this <div> will be referenced by some javascript getElementById() method?
Maybe you should check out the differenc between ID's and Classes:
http://css-tricks.com/the-difference-between-id-and-class/
I have never heard of using classes only in CSS and ID's only for JavaScript.
The main thing is ID's are unique, thats why they are called identifiers. If you have the same styling of a div over and over again on your webpage you should use a class to style them.
EDIT: It's not common or maybe its not allowed, I'm not sure, that ID's start with a number !
You can use id and / or class in JS and / or CSS. It all depends what you want to select. If you want to select a single DOM element, feel free to use id. If you want to select a group of related elements you might be better off using class.
Id should(read: must) be unique. A class is a set of object that have similarities, for example all lists on the page should look the same (but then you should use the list selector instead of a seperate class for it.
They have different purposes.
Specifically, a class or id within the css.
Would you use something similar to $(window).height()?
It's not clear exactly what you want, but as a general rule all the styles applied to a given element can be accessed in JavaScript using something like:
element.style.<property-name>
So using native JavaScript you can do:
var elemStyles = document.getElementById("someId").style;
var styleWidth = elemStyles.width;
Assuming at least one element with a given CSS class and a framework that can select elements by class, you can similarly do:
var elemStyles = $(".someClass")[0].style;
var styleWidth = elemStyles.width;
Or depending upon what (if any) JavaScript framework you are using, there may be specialized methods that you can use to access/inspect various CSS attributes for a given element.
Note that any of these methods will bring back all the styles applied to the element, whether they are coming from the CSS file, from inline CSS declarations, or added programmatically by a script on the page. If you want to get just the styles inherited from the CSS file, then things get a bit trickier.
yes its possible
if you would like to receive other css properties check this out
http://api.jquery.com/css
you would do somethig like this
var cssvalue = $(selector).css(propertyName);
This will probably help you, too. Esp. if you want to do it without jQuery: How do you read CSS rule values with JavaScript?