How to use Javascript to add multiple style properties to one element? - javascript

I've tried various renditions of this code to try and change a certain element for a coding exercise but non of them seems to be able to change multiple styling properties of an element on a button click. Would love some assistance. Thanks!
document.getElementById("Combo Style").onclick = function() {
document.getElementById ("More Text").style.fontSize.color = "50px , #BB65C5";
}

You can use cssText property but it will change the styling for the element completely
Style cssText Property
document.getElementById("myP").style.cssText = "background-color:pink;font-size:55px;border:2px dashed green;color:white;"
This will overwrite the existing css styling for that element , so make sure you included every needed property.

To achieve your expected result use setAttribute
HTML:
<button id="Combo Style">Change</button>
<div id="More Text">abcd</div>
JS:
document.getElementById("Combo Style").onclick = function() {
document.getElementById("More Text").setAttribute("style", "font-size:50px;color:red;");
}
http://codepen.io/nagasai/pen/AXVWwO

You need to grab the element by using id or any selector and use style property or css text property to apply css. Check the below code -
var element=document.getElementById("More Text");
element.style.fontSize="20px";
element.style.color="red";
element.style.background="blue";
You can also use cssText property, like -
document.getElementById("More Text").style.cssText='fontSize="20px";color="red";'
This will insert an inline style tag in the element with the csstext property.

Related

Mark an elements with CSS in order to later detect them with JS

I am using CSS selectors to match certain elements and I would like to detect those elements with javascript.
I figured out I can set the color in css of those element and later retrieve them by color.
The problem is style.backgroundColor returns only the if inline style is set.
Here is my try
http://jsfiddle.net/qUDjb/29/
CSS
div{background-color: lightgrey;}
JS
alert(document.getElementById("myDiv").style.backgroundColor);
Is there a way to make color detection to work or maybe somebody has a better idea on how to detect affected elements (by css selectors)?
I prefer not to use jquery for this.
element.style only returns inline style declarations (or declarations added in JS using elements.style['foo'] = "bar". It isn't always the rule that's applied by the browser, for example a CSS declaration with !important can override inline styles. You can also have multiple CSS declarations that overwrite one another and the browser decides which one to apply using CSS selector precedence rules.
To get what rule has really been applied you should use getComputedStyle method: http://jsfiddle.net/qUDjb/31/
window.getComputedStyle(document.getElementById("myDiv"))['background-color']
MDN on getComputedStyle
EDIT: if you want to get elements by background color it wouldn't really be the best way, but it's possible to get a collection of elements, then filter by the computed style value: http://jsfiddle.net/qUDjb/36/
CSS
p:nth-child(2n) {
background-color:lightgrey;
}
JS
var getElementsByBackgroundColor = function( collection, color ){
// convert the color string to the format used by browser
var div = document.createElement('div');
div.style.backgroundColor = color;
var computedColor = div.style.backgroundColor;
// compare computed background color and return matching elements
return [].slice.call( collection ).filter( function( item ){
return window.getComputedStyle( item )['background-color'] == computedColor;
});
}
console.log( getElementsByBackgroundColor( document.querySelectorAll('p'), 'lightgrey') );

How to access inline css style atribute and change proprties in DOM using jquery?

I need to change the DOM dynamically. I want to access the 'text-align' and the 'line-height' properties.
for example:
<p style="line-height:1.0;text-align:justify;">
I need to access all the style attributes in the DOM and go through each 'text-align' and 'line-height' properties and change their values. How to access these properties.
Actually what I need to do is go through these two properties and change the text-align to left and change the line-height to 1.5 if it's less than 1.5
Thank you so much inadvance.
You can use $("#selector").css({'property' : 'value'});
from the docs : http://api.jquery.com/css/
You can set properties using this method.
Edit :
to check if an element has a css style, you can use the following SO answer :
jQuery: check if element has CSS attribute
You can use .css method to achieve this:
$('p').css({'lineHeight':'1.0','textAlign':'right'})
Update:
If you want to select all elements that has line-height style you can use following selector:
$('*[style*="line-height"]').css({'lineHeight':'1.5'})
Try:
$(document).ready(function(){
$("*").each(function(){
alert($(this).css('lineHeight'));
if($(this).css('lineHeight')){
$(this).css({'lineHeight':'1.0'});
}
if($(this).css('textAlign')){
$(this).css({'textAlign':'right'});
}
});
});
Here $("*") will select all elements in DOM and then .css("propName") will check whether the propName property exists in that element's css. and if it exists then .css({'propname':'newValue'}); will assign a new value to that property.
Hope it helps.
As mentioned before, you can use:
$('p').css({'lineHeight':'1.0','textAlign':'right'});
You can also use:
$('p').css('lineHeight', '1.0');
$('p').css('textAlign', 'right');
Although not recommended, because this would replace all other styles, you could even do:
$('p').attr('style', 'lineHeight: 1.0; textAlign: right;');
To select all elements on the dom, just use the $('*') selector.
$(document).ready(function(){
$("*").each(function(){
// 1.0 == 16px | 1.5 == 24px
if(parseInt($(this).css('lineHeight'), 10) < 24){
$(this).css({'lineHeight':'1.5'});
}
});
});
HERE is the JSFiddle

select element with prototype

how can I select the following element using prototype div#page_container h1 and after selecting it change its padding-top ? Thank you
Prototype's $$() method allows you to select using CSS selectors, eg
var elmArr = $$("div#page_container h1");
and its setStyle method allows you to change style, eg
elmArr[0].setStyle({paddingTop: "4px"});
or
$$("div#page_container h1")[0].setStyle({paddingTop: "4px"});
Edit: I'm pretty sure the returned array is also extended by prototype, so if you had multiple h1 elements in page_container, you could do:
$$("div#page_container h1").each(function(elm){
elm.setStyle({paddingTop: "4px"});
});
or
$$("div#page_container h1").invoke("setStyle",{paddingTop: "4px"});
to set the paddingTop of all of them
Make sure you include these .. and it should work , from this source
Cheers

Create a div containing target div using jQuery

I think that this should be easy, but I'm not able to get it working. I want to target a div or other element using jQuery and then dynamically create a div containing the targeted element, for example:
jQuery ('.myclass')
How can I create a div with the background-color attribute set to white that contains 'myclass' element?
Initially I have: <div class="myclass">Some HTML elements inside</div>
And after executing the jQuery call i want to have: <div style="background-color:#fff"><div class="myclass">Some HTML elements inside</div></div>
I hope that you understand my question...
You can use the wrap function to put a wrapper around the matching elements. I'd prefer to use a class for the background, but you can assign CSS properties directly as well.
$('.myclass').wrap( $('<div></div>').css( 'background-color', '#fff' ) );
or
$('.myclass').wrap( $('<div></div>').addClass('white-background') );
var $myDiv = $('<div>').css('background-color','#fff').append( $('.myclass') );
You can then write this variable to the DOM as you see fit, or do whatever else you need to do.

How to change css properties of html elements using javascript or jquery

How can I change CSS from javascript.
I'm using jQuery-ui Dialog and I want to change the style of a DIV from javascript.
Thanks
Check out the jQuery documentation. If you want anything it will be there.
Anyhow, if you want to add styles to elements, you need to use the css function, which has a few variants.
$(selector).css(properties); // option 1
$(selector).css(name, value); // option 2
So if you have a DIV with ID of "mydiv" and you want to make the background red, you would do
$("div#mydiv").css({'background-color' : 'red'}); // option 1
$("div#mydiv").css('background-color','red'); // option 2
The first way is easier if you're setting multiple things at once.
If you want to check what a property is currently set to, you would use a variant of the 2nd option, just omit the value.
var color = $("div#mydiv").css('background-color');
Would make the var color be red if you already set it above, for example.
You can also add and remove classes, doing something like
$(selector).addClass(class_name);
$(selector).removeClass(class_name);
This answer works even without jQuery.
So you have something like this:
<style type="text/css">
.foo { color: Red; }
.bar { color: Blue; }
</style>
<div class="foo" id="redtext"> some red text here </div>
If you wish to change just some attributes, you can always find the element using
var div = document.getElementById('redtext');
function and then change the attached color style by
div.style.color = 'Green';
Making your red text appear in green instead.
If you want to change the class defined for the div to another style class, you can do:
div.className = 'bar';
making the div now use class bar, which makes your previously green text blue.
There are a couple of ways to manipulate elements styles using the jQuery framework. Take a look through the documentation related to CSS and changing attributes:
http://docs.jquery.com/Attributes/addClass#class
http://docs.jquery.com/CSS
Try this.This is jquery code.
$("myDiv").css({"color":"red","display":"block"})
If you are using vanila javacript,try this.
var myDiv = document,getElementById("myDiv");
myDiv.style.display = "block";
myDiv.style.color = "red";

Categories

Resources