In CSS we can do:
div { font-size:20px }
To set the default font size for all divs. Is there a way to change default styles for elements with JavaScript?
Alternately, how could I find and set the above style rule? You can find classes by searching document.styleSheets[0].cssRules by name, but I don't know how to find the style for div.
EDIT:
Oops, the answer is in my question.
My confusion arose from attempting to alter rules that were set for multiple elements at once.
So you would be able to find and alter the CSS rule for div as above.
What I don't know is how you'd alter the rule for multiple definitions:
div,span { font-size:20px }
You can't find the rule by searching for div, span or div,span.
You can use style.fontSize property for setting font size using javascript. The code will look like
document.getElementById("//id here").style.fontSize = "50px"; //size
See an example here
well if you want to change the style of an determinated div you have to do this in you javascript code
getElementById('div_register').setAttribute("style","font-size:20px");
in this way you are getting de div by its id, and setting a style that you want, you can set differents styles with these and will save code space as declare one by one the style you want...i hope i helped you :-D
With the help of javascript you can change the DOM properties. You can create one outer div and give it some name/id. Then, loop through all inner divs and update the css style attributes.
innerDivs = document.getElementById('odivID').getElementsByTagName('div');
for (var i = innerDivs.length-1; i >= 0; i--) {
innerDivs[i].style.fontSize = "25px";
}
You can do this by n number of ways, but I recommend to use class name:
style
div.my-style {
font-size:20px;
}
script
...
var divs = document.getElementsByTagName('div');
var len = divs.length;
var cn;
if(len --) do {
cn = divs[len].className;
if(cn) {
cn += ' my-style';//<-- spaces to separate with the existing class names, if any
} else {
cn = 'my-style';
}
divs[len].className = cn;
} while(len --);
...
Note: Applying style to all divs will apply to those divs as well on the same page which you don't want to do.
You could create your own css style rule that override the default one.
either
create <style> in <header> using javascript
or, link external css file <link>
please see fiddle using first method: http://jsfiddle.net/b8Hn7/
var myStyle = document.createElement("style");
myStyle.innerText = 'div { font-size: 40px; }';
document.head.appendChild(myStyle);
The above code overrides the default style by creating same rule but place after the default style, there is no need to "locate" the default style and change it.
U can try it with create 'style' dom like my under code:
html:
</div>
js:
var style = document.createElement('style');
style.innerText = 'div{width:100px;height:100px;border:1px solid #c4e;}';
document.body.appendChild(style);
Related
The following code is an example of open and close actions of a sidebar, where some CSS values should be updated to correctly show the sidebar.
function openNav() {
document.getElementById("sidebar").style.width = "250px";
document.getElementById("mainContent").style.marginLeft = "250px";
document.getElementById("codePanel").style.marginLeft = "10px";
}
function closeNav() {
document.getElementById("sidebar").style.width = "0";
document.getElementById("mainContent").style.marginLeft = "0px";
document.getElementById("codePanel").style.marginLeft = "40px";
}
Now I ask myself if there is a better way to do this if I eg update more different styles?
Because in this code, I would need to add more and more similar looking lines of code which looks really clunky.
If you add an initial class to all your elements that you want to update
<div id="sidebar" class="update"></div>
<div id="codePanel" class="update"></div>
Then add some styles (be aware of style specificity)
#sidebar.update {
width : 200px;
}
#sidebar.update.updated {
width : 250px;
}
#codePanel.update.updated {
color : red;
}
You can easily add that class to multiple elements in a loop
var elems = document.querySelectorAll('.update');
elems.forEach(function(elem) {
elem.classList.add('updated');
});
as the other members mentioned it is better to use class, what I want to add is
that you can create those css classes based on specific style for example create a class called marginLeft50 which sets the left margin to 50 so whenever you want to update an element css you can simply do $('sidebar').addClass('marginLeft50');
keep in mind that you can add multiple classes to a single element, and since you mention jquery in your tags, jquery takes care of looping through all the targeted elements and updating each one of them
and as simply you can $('selector').removeClass('className') whenever you need to
I got an user provided html saved in database "with or without" css font-size specified.
And try to make a button to enlarge or decrease the font-size on the doms but maintain the
relative size.
I defined an variable def_size to be 16px and cur_size to be the base size on the fly.
But I dont know how to deal with the dom with size predefined?I tried the preg_replace,but it failed.
http://jsfiddle.net/95kDZ/
function change_font_size(csize){
var $cotent_html=$('.content');
cur_base=cur_base+csize;
//without style,just add the css to the whole div"
$cotent_html.css('font-size',cur_base.toString()+'px');
/*
Please give me some hint.Thanks
I think you need to get every element that could contain text: p, span, div, etc and apply your font-size logic on it instead on the whole html root. You need to target specific html element in order to overwrite its style.
Updated working fiddle here.
Code:
var def_size=16,
cur_base=def_size;
$('input[type="button"]').click(function() {
change_font_size(parseInt($(this).data('csize')));
});
function change_font_size(csize){
var $cotent_html=$('.content');
cur_base=cur_base+csize;
//without style,just add the css to the whole div"
$cotent_html.find('span, p, div').css('font-size', cur_base.toString()+'px');
}
A foreach function would be better for this
Here is the updated fiddle
Code:
function change_font_size(csize){
var $content_html=$('.content p, .content span');
$content_html.each(function(){
var cur_size = parseInt($(this).css('font-size'));
cur_size += csize;
console.log(cur_size);
$(this).css('font-size', cur_size.toString()+'px');
});
}
I have a Element with the id="somID";
For Example:
Html:
<div id='somID' ></div>
Css :
#somID{ width:500px;height:500px}
and i have a class named : maximize.
So,
.maximize{width:100% !important; height:100% !important; }
Now dynamically i added the class .maximize to my div #somID
And after that i wanna get the width and height of my #somID by calling with its ID like,
$('#somID').width() or .height()
but i want to take the actual height of element that is defined in its ID but i get the .maximize in result not the height or width that is in #somID.
Any buddy have any idea ? That how to retrieve the height of div#somID if it contains .maximize ??
The problem is, there can be many, many selectors that are applied to a given element, with different specificities. There is no API that allows you to request a property from a selector in CSS - it simply wouldn't make much sense.
Having said that, you can create a hack to solve that issue:
function getOriginalDimensions(id) {
var $a = $("<div>", {id:id});
$("body").append($a);
var width = $a.width();
var height = $a.height();
$a.remove();
return {width:width, height:height};
}
console.log(getOriginalDimensions("somID")); // returns {width:500, height:500}
The above works with your example HTML and CSS.
JSFiddle
This basically creates an element with the same ID, appends it to the body, reads the dimensions and deletes it immediately. This is necessary because the div will have no size if it is just kept as a document fragment and not added to the DOM, because the CSS will not get applied.
In theory you could expand this function to make it work with other selectors.
However bear in mind this is a nasty hack and you should reconsider your approach.
A. Make your measurements and save them as .data attributes of the element :
var $el = $('#somID');
$el.data('original_dims', {
height: $el.height(),
width: $el.width()
}
B. Add class that changes the dimensions of the element :
$el.addClass('maximise');
C. Retrive the original dimensions whenever they are needed
var h = $el.data('original_dims').height;
var w = $el.data('original_dims').width;
Here is nice piece of code that works fair in all browsers: http://www.imaputz.com/cssStuff/bigFourVersion.html
Since there are things that need to be computed for every particular table (extra space for scrollbar, fixed width for every cell), I'd like to create a javascript that modifies the table to make it scrollable.
Such scripts already exist, i.e. http://www.farinspace.com/jquery-scrollable-table-plugin/
but all of them need to specify the height of the table. I'd like to extract the height from CSS to make the script unobtrusive.
If I write the height as inline style, all browsers can read the table.style.height property. But when external style is used
<style>
.scrollTable { display: block; overflow: hidden; height: 200px; }
</style>
only Firefox can read the offsetHeight/clientHeight property as expected. Other browsers can't change table layout to block, I guess.
The only thing that I figured out is to read external CSS
function getCSS(rule,prop) {
if(!(document && document.styleSheets)) return;
var result="", ds = document.styleSheets;
for(var i=0; i<ds.length; i++) {
var r = getCSS1(ds[i],rule,prop);
if(r) result = r;
}
return result;
}
function getCSS1(sheet,rule,prop) {
var rules = sheet.cssRules? sheet.cssRules: sheet.rules;
var result = "";
for(var i=0; i<rules.length; i++) {
var r = rules[i].selectorText.toLowerCase();
if(r.indexOf(rule)==-1) continue;
if(r.lastIndexOf(rule)!=r.length-rule.length) continue;
var p = rules[i].style[prop];
if(p) result = p;
}
return result;
}
var height = getCSS(".scrollTable","height");
But the height might be specified otherwise: by id, another class or inherited, so I am probably in wrong way. Is there any other way how to guess the table height? I am about to give up.
In short
I want this code
<script src="scrollTable.js"></script> // load the script
<style> .scrollTable { height: 200px; } // set the CSS
<table class="scrollTable">...</table> // script should do all the tricks
My script can do all the tricks except for get the table height. How to extract it?
Why not enclose the <table> in a <div>? This way you should be able to the get the <div> height even if it's in an external CSS.
With jQuery you can use .css() function:
table_height = $("table.scrollTable").css("height");
This will return the height of your table including px. So you can extract only the number with some other javascript function.
Assuming you are using jQuery (you did mention a jQuery plugin), you can calculate the height of an element using $('table.selector').height().
Is getComputedStyle the answer ? See here : http://blog.stchur.com/2006/06/21/css-computed-style/
You could use
document.getElementById("ID").clientHeight
It worked for me in IE8 and Chrome when I tested height set via
html
inline style
style sheet
Here's what I did:
<table height="350" id="one">
<table>
<table style="height:400px;" id="two">
<table>
<table class="height" id="three">
<table>
and
alert(document.getElementById("one").clientHeight);
alert(document.getElementById("two").clientHeight);
alert(document.getElementById("three").clientHeight);
Working example: http://jsfiddle.net/jasongennaro/h9B2j/
EDIT
Something else must be interfering with the code, I think, as
document.getElementById("").clientHeight;
works for me even without the height being set.
See another example here: http://jsfiddle.net/jasongennaro/h9B2j/2/
How should I do this in Javascript?
// CSS
*::-moz-selection{
background:transparent;
}
I tried these but doesn't really works:
// Javascript
document.mozSelection = "transparent";
document.body.mozSelection = "transparent";
You can add a rule to the stylesheet.
// Get the first stylesheet
var ssheet = document.styleSheets[0];
if ("insertRule" in ss) {
ss.insertRule('#yourdivcontainer::-moz-selection { background: transparent; }', 0);
}
IMO, it's not a good practice anyway. You should create a CSS class with the selection color and change the class itself via JS instead of the style.
:: selectors are for pseudo-elements, CSS objects that don't correspond to actual element nodes. Because there is no element node to match ::-moz-selection, you can't style it directly on an element's .style.background property.
Instead you would have to insert a new stylesheet rule duplicating the above CSS (see this question for a couple of methods of doing that).