Getting style of an element from css file with javascript - javascript

I wanna get a style of an element from css file with javascript. But, i just can getting only elements i enter style properties on javascript. I tried like this on Angular;
angular.element(document.getElementById("box")).css("width")
It's not worked. After, i tried like this;
document.getElementById("box").style
But it's not worked. How can i accomplish this?

This isn't an Angular issue, it's just how CSS and Javascript interact. You need to use getComputedStyle to read style properties that were defined in a CSS file.
// This will work (because it's an inline style)
console.log(document.getElementById('a').style.width)
// This won't work (because the style was defined in css):
console.log(document.getElementById('b').style.width)
// getComputedStyle will work regardless of the source:
console.log(window.getComputedStyle(document.getElementById('b')).width)
#b {width: 100px}
<div id="a" style="width: 100px">A</div>
<div id="b">B</div>

You cannot get css template rule values of elements calling style properties unless they were set
*1. using inline style on html element level; or
*2. the style property has been set using JavaScript
which does the same: writes to inline html style property of the target element.
the solution is to use the computed style instead:
as in : getComputedStyle(box,0).width

Related

Does CSS code initialize .style properties of DOM objects?

Background:
I created a simple DOM event example: see jsfiddle here.
<div id="squirrel" onmouseover="toggleFloat(this)">
<p>Click me!</p>
</div>
<script>
function toggleFloat(ele){
var current = ele.style.cssFloat;
console.log("cssFloat: "+current);
if(current==="left")
ele.style.cssFloat="right";
else
ele.style.cssFloat="left";
}
</script>
Accompanying css:
#squirrel{
float:left;
}
Odd behaviour was noticed: In the DOM, the #squirrel's initial value for the cssFloat property was "". (Open the developer console to see this. Or notice that the #squirrel doesn't move until the second event fires.).
My question is: Should the CSS code not have initialized the cssFloat property of the DOM object? ...or any of the style properties for that matter?
The style property of an element represents its inline style (defined with the style attribute).
Those are not modified by the css rules defined in a your css file. The browser computes the final style based on those rules and the inline style.
The final computed style can be retrieved using MDN: Window.getComputedStyle()
You generally should avoid to use inline style attributes. Normally you should try to use class to manipulate the appearance of a certain element. Also the use of the style property to dynamically change the inline style should only be used if there is really no way around it, e.g. if you need to move an element dynamically. You could also read the answer to Inline tags vs. inline css properties for more informations.
CSS never modifies the DOM.
The 'style' attributes in the DOM are merged-with/override the CSS defined in stylesheets.

Change css class atributes dynamically from Jquery?

I have a situation in my project , in css I have a class
which is empty for now
#version_mobile.hidden
{
}
and in js Im doing this
this.$("#version_mobile.hidden").css({right: - window.text_mobile_width});
(I supose my selector is bad ?)
how to add "right" atribute to this class with this dynamically created value ?
to class become
#version_mobile.hidden
{
right : -450px;
}
Btw I need to use this class because the animation is working with it :/
.css() function changes the inline css style but has no effect over the css classes at all.
As pointed out in the documentation:
When using .css() as a setter, jQuery modifies the element's style
property.
You can also change the classes by using the addClass(), removeClass() or even the toggleClass() functions of jQuery.
You cannot add to the class properties, but you can apply rules to the element style.
this.$("#version_mobile.hidden").css({"right", "- window.text_mobile_width"});
you can not add definations for class in jquery.
but you can add any style to your selecter.
What are you trying to achieve?
you cannot add a property to the css file using this.
what you should look at is you apply this id or class to your html elements
and access the elements in the javascript using the jquery selectors
$(#selector) and modify the property using .css.
So you will achieve the same result this way as any existing property style for that
element will be overridden with your latest style put through the jquery.
It's technically possible to modify style rules on the fly, but it's difficult.
In the document object you will find an (array) property called styleSheets, with one entry for each referenced stylesheet.
Each stylesheet object (of type CSSStyleSheet) has an insertRule method, which you can use to create new rules, or delete existing rules. What appears to be difficult is enumerating the existing set of rules so you can find which one to modify or delete.
That said, it's generally far preferred to simply change an element's classes than to try to dynamically change the styling of an existing class.
See also http://davidwalsh.name/add-rules-stylesheets

which one is given more preference for JavaScript or CSS?

here is my code
<!doctype html>
<html>
<head>
<style>
body {
color:red;
}
</style>
<script>
window.onclick = function(){
document.getElementsByTagName("body").color="blue";
}
</script>
</head>
<body>
here is some text for test
</body>
when i run it in my browser (initially it is red) and click in window it doesn't respond to click i mean it should change the color of text from red to blue but nothing happens. Where am i wrong?
Try this:-
Demo
This will add style attribute to the body element, which will override the css rule.
window.onclick = function(){
document.getElementsByTagName("body")[0].style.color="blue";
}
It should be style.color as color is a property of style property of element and even though it is body .getElementsByTagName returns a collection so you need to use document.getElementsByTagName("body")[0] to get the element and apply style to it.
And yes styles applied the element direclty will override the class css rule
Style property has more precedence over styles applied by class.
document.getElementsByTagName("body").color="blue";
This has more preference
Also color is a property of style attribute.
So your style should have looked something like this as getElementsByTagName returns a node list.
document.getElementsByTagName("body")[0].style.color="blue";
it is a better idea to use classes instead, cause it is lot cleaner.
Inline CSS is more powerful and overrides CSS defined anywhere else.As far as working of your code, I modified it a little bit like this:
window.onclick = function(){
//document.getElementsByTagName("body").color="blue";
document.body.style.color="blue";
}
DEMO here
You have an error in your JS. getElementsByTagName returns a NodeList (which is like an array), not a single element. You need to set the property on an element, not a NodeList. For example:
document.body.color="blue";
Setting the color property of the body element (IIRC, it's been a very long time since I went near that part of HTML) is equivalent to setting the color attribute. This is an obsolete presentational hint attribute.
The CSS specification says:
The UA may choose to honor presentational attributes in an HTML source document. If so, these attributes are translated to the corresponding CSS rules with specificity equal to 0, and are treated as if they were inserted at the start of the author style sheet. They may therefore be overridden by subsequent style sheet rules. In a transition phase, this policy will make it easier for stylistic attributes to coexist with style sheets.
So the style specified in the stylesheet should continue to apply.
On the other hand, setting a style.something property is equivalent to modifying the style attribute on an element.
document.body.style.color="blue";
In the cascade, !important declarations aside, properties set via the style attribute are most specific.
So of those two rules, the blue one would win.
JS inserts the changes inline, giving them pretty much the highest priority, unless you have !important in your css.
Check to see if you code (document.getElementsByTagName("body").color="blue";) works from the dev console (F12 for Chrome). There appears to be a problem with it. I can't help debug, however, as I usually do such actions via jQuery, and vanilla JS color changes are unintuitive for me.
js and css does not compete with each other, what you are doing is essentially javascript applying css to an html element, this means that its still css, that type of css is called inline css, . As others have said inline css has more precendence over normal css except if you use !important in your css rules
As to why your code is not working, because you are doing it wrong.
Change
document.getElementsByTagName("body").color="blue";
To
document.getElementsByTagName("body")[0].style.color = 'blue';
Here's a jsFiddle
http://jsfiddle.net/n2kqd/

how to avoid looking css property using jquery or javascript

There is some content in html page and one of div style for that is like below:
.class1{
property1:value1;
property2:value2;
property3:value3;
property4:value4;
}
I want to avoid applying css property property1 into concerned content and rest property property2, property3, property4 are welcomed.
I want to avoid applying property1 and don't want to change the css file.
Also I don't want to use as below:
$('.class1').css('property1','some different value');
I just want to avoid property1 using code.
Please tell me how I done using jquery or js.
----------------------Edited------------------------
I don't want to generate any inline css on run time.
I am looking ui code some thing like as below:
$('.ui-resizable').css('position').disable()
There is not function avaialbe to do that , one way to achieve this is
$('.class1').css('property1','');
Just set an inline style on the element that negates the property or makes it what you want. No jQuery necessary. Inline styles will always override inherited styles.
<div class="class1" style="margin:whatever"></div>
Make another class "class2" with css and use
/* CSS */
.class2{
property1:value1;
}
//JQuery
$('div').removeClass('class1').addClass('class2');
Preserve the value of property1 as:
var p1 = $('.class1').css('property1');
Now apply changes to the class as necessary.
Finally, restore the value of property1 as:
$('.class1').css('property1',p1);

change the Style Attribute value

How can I get and change the Style Attribute property value
Example
<div id="styleChanger" style="color: rgb(163, 41, 41);">
// some content
</div>
How can I change the Style property color value
Every CSS declaration, inline (a.k.a style attribute), in the page header or in an external file, is just incorporated into the DOM object attributes once the browser has read it.
This is to say that you're not actually interested in changing the style attribute, but an attribute of the object you're working on in Javascript. For CSS attributes, jQuery's .css() method is the answer.
$('#styleChanger').css("color","red");
You need a ready class, for example:
.interactClass {
color: #d2232a;
}
and then you can
$('#styleChanger').removeClass().addClass('interactClass');
Or you can switch single properties with css method:
$('#styleChanger').css("color", "#D2232A").css("font-size", "20px");
Use the css() method in jQuery. Here is a link to the documentation: http://docs.jquery.com/CSS/css#name
This will allow you to do something like:
$("#styleChanger").css("color", "#888888");

Categories

Resources