I've created the following...
var menu = document.createElement('select');
How would I now set CSS attributes e.g width: 100px?
Use element.style:
var element = document.createElement('select');
element.style.width = "100px";
Just set the style:
var menu = document.createElement("select");
menu.style.width = "100px";
Or if you like, you can use jQuery:
$(menu).css("width", "100px");
For most styles do this:
var obj = document.createElement('select');
obj.style.width= "100px";
For styles that have hyphens in the name do this instead:
var obj = document.createElement('select');
obj.style["-webkit-background-size"] = "100px"
That's actually quite simple with vanilla JavaScript:
menu.style.width = "100px";
Just for people who want to do the same thing in 2018
You can assign a CSS custom property to your element (through CSS or JS) and change it:
Assigment through CSS:
element {
--element-width: 300px;
width: var(--element-width, 100%);
}
Assignment through JS
ELEMENT.style.setProperty('--element-width', NEW_VALUE);
Get property value through JS
ELEMENT.style.getPropertyValue('--element-width');
Here useful links:
https://developer.mozilla.org/en-US/docs/Web/CSS/--*
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/getPropertyValue
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/removeProperty
All of the answers tell you correctly how to do what you asked but I would advise using JavaScript to set a class on the element and style it by using CSS. That way you are keeping the correct separation between behaviour and style.
Imagine if you got a designer in to re-style the site... they should be able to work purely in CSS without having to work with your JavaScript.
In prototype I would do:
$(newElement).addClassName('blah')
When debugging, I like to be able to add a bunch of css attributes in one line:
menu.style.cssText = 'width: 100px';
Getting used to this style you can add a bunch of css in one line like so:
menu.style.cssText = 'width: 100px; height: 100px; background: #afafaf';
if you want to add a global property, you can use:
var styleEl = document.createElement('style'), styleSheet;
document.head.appendChild(styleEl);
styleSheet = styleEl.sheet;
styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);
<h1>Silence and Smile</h1>
<input type="button" value="Show Red" onclick="document.getElementById('h1').style.color='Red'"/>
<input type="button" value="Show Green" onclick="document.getElementById('h1').style.color='Green'"/>
This works well with most CSS properties if there are no hyphens in them.
var element = document.createElement('select');
element.style.width = "100px";
For properties with hyphens in them like max-width, you should convert the sausage-case to camelCase
var element = document.createElement('select');
element.style.maxWidth = "100px";
<body>
<h1 id="h1">Silence and Smile</h1><br />
<h3 id="h3">Silence and Smile</h3>
<script type="text/javascript">
document.getElementById("h1").style.color = "Red";
document.getElementById("h1").style.background = "Green";
document.getElementById("h3").style.fontSize = "larger" ;
document.getElementById("h3").style.fontFamily = "Arial";
</script>
</body>
Related
I'm new to frontend development, and I want to rezize an <img> with JavaScript:
Which element?
<div class="dz-image">
<img data-dz-thumbnail="" alt="principal.png" src="http://localhost:49407/file/Image/660">
</div>
What function im using in js?
this.emit("thumbnail", mockFile, "http://localhost:11111/file/Image/" + principal)
{ document.querySelector('data-dz-thumbnail') };
I'm using querySelector to get the spefic <img> element.
Is it possible to add some style directly on that line like height:120; width: 120;?
Yes,it is possible to add some style directly.
let ele = document.querySelector('[data-dz-thumbnail]')
ele.style.width="120px"
ele.style.height="120px"
Per my understanding, queryselector should be classname, id or tag
Second you can add css by taking a variable for your querySelector line. It is like:
var el = document.querySelector('div');
el.style.backgroundColor = 'green';
el.style.display = 'none';
el.style['border-radius'] = '5px';
I solved this using jQuery's .css() method like this:
$('[data-dz-thumbnail]').css('width', '120');
$('[data-dz-thumbnail]').css('height', '120');
On my project I use JS Buttons a lot, I can't find a way to add CSS to them. Can you help?
leftBtn = document.createElement('button');
leftBtn.innerText = "<";
rightBtn = document.createElement('button');
rightBtn.innerText = ">";
fireBtn = document.createElement('button');
fireBtn.innerText = "*";
Using CSS classes to change buttons:
<button class="btn">default button</button>
Class used
You could use this code to add a css class to each button:
leftBtn.className = "leftOne";
rightBtn.className = "rightOne";
fireBtn.className = "fireOne";
Then you can use regular css to style them.
You could add a class to your buttons, and then add any styling in CSS:
leftBtn.className = "class_name"
You probably need to use the className to your Javascript:
EXAMPLE:
leftBtn.className = "name";
Hope this helps :)
you can use for example :
leftBtn.style.color = "blue";
Lear more about in https://developer.mozilla.org/es/docs/Web/API/HTMLElement/style
In general, there are two main ways to do that.
The first one using inline styles, just keep in mind that inline style has the highest precedence in a document.
elt.style.color = '...'
or
elt.setAttribute('style', '...')
More info here
The second is by using the class name. You can simply define a class name and write CSS for this class name.
element.className.add = 'your-class-name'
then
.your-class-name { color: red }
In a second way, you can manage class names by using methods like add, remove, toggle
More info here
Just do something like this
leftBtn.style.marginLeft = '20px'
rightBtn.style.marginLeft = '20px'
I guess it
var leftBtn = document.createElement('button');
leftBtn.innerText = "<";
leftBtn.className = "test_style"; // Set class name
leftBtn.style.color = "#000"; // You can also set style properties inline
...
Here is a playground:
https://jsfiddle.net/u5hojsgb/
Hi I'm new to JavaScript and CSS and I would like to create a JavaScript function that dynamically applies the style properties that are defined inside this function to a specific element.
Please check my code below, I have managed to create the element and add the class to that element but I'm struggling to implement the style properties inside this function.
function highlight(){
var styl = document.querySelector("#element_to_pop_up");
styl.style.cssText = " background-color:#fff;border-radius:15px; color:#000;display:none;padding:20px;min-width:30%;min-height: 30%;max-width:40%; max-height: 40%;";
styl.className = styl.className + "b-close";
//.b-close{
//cursor:pointer;
//position:absolute;
//right:10px;
//top:5px;
//}
}
Please any help will be highly appreciated.
If you want to add a style class to your page and write its style content, you should create it first then put it in a <style> tag, so you can use it later.
This is your way to go:
function highlight() {
var styl = document.querySelector("#element_to_pop_up");
//Create StyleSheet
var styleSheet = document.createElement("style");
var text = document.createTextNode("\n.b-close {\n cursor:pointer;\n position:absolute;\n right:10px;\n top:5px;\n}");
//Put the style on it.
styleSheet.appendChild(text);
//Append it to <head>
document.head.appendChild(styleSheet);
//Apply it
styl.className = styl.className + " b-close";
}
<div onclick="highlight()" id="element_to_pop_up">bla bla bla</div>
Create a Style Sheet Element.
Put the style on it.
Append it to the head of the document.
Use this style or apply it to element.
EDIT:
If you will pass the style top and right values as parameters to the function just do the following:
function highlight(right, top) {
var styl = document.querySelector("#element_to_pop_up");
var styleSheet = document.createElement("style");
var text = document.createTextNode("\n.b-close {\n cursor:pointer;\n position:absolute;\n right: "+right+"px;\n top: "+top+"px;\n}");
styleSheet.appendChild(text);
document.head.appendChild(styleSheet);
styl.className = styl.className + " b-close";
}
Use jquery insted on javascript.
$(selector).css("width":"100%").css("height","100px");
You can just add a CSS class (and style it in your stylesheet instead of your javascript).
Here is an example (there are multiple way to do it but I don't know what your try to achieve exactly) :
function highlight(){
var target = document.getElementById("header");
target.className = target.className + " highlighted";
}
var btn = document.getElementById('add-class');
btn.addEventListener('click', highlight);
.highlighted {
/*Your CSS*/
background-color: red;
}
<h1 id="header">Lorem</h1>
<button id="add-class">Click me</button>
Edit: If you want to use jQuery, it's even simpler :
$(document).ready(function() {
$('#add-class').on('click', function() {
$('#header').toggleClass('highlighted');
});
});
.highlighted {
/*Your CSS*/
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="header">Lorem</h1>
<button id="add-class">Click me</button>
I hav a certain style sheet for a div. Now i want to modify one attribute of div dynamically using js.
How can i do it?
document.getElementById("xyz").style.padding-top = "10px";
Is this correct?
In addition to other answers, if you want to use the dash notition for style properties, you can also use:
document.getElementById("xyz").style["padding-top"] = "10px";
It's almost correct.
Since the - is a javascript operator, you can't really have that in property names. If you were setting, border or something single-worded like that instead, your code would work just fine.
However, the thing you need to remember for padding-top, and for any hyphenated attribute name, is that in javascript, you remove the hyphen, and make the next letter uppercase, so in your case that'd be paddingTop.
There are some other exceptions. JavaScript has some reserved words, so you can't set float like that, for instance. Instead, in some browsers you need to use cssFloat and in others styleFloat. It is for discrepancies like this that it is recommended that you use a framework such as jQuery, that handles browser incompatibilities for you...
There is also style.setProperty function:
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty
document.getElementById("xyz").style.setProperty('padding-top', '10px');
// version with !important priority
document.getElementById("xyz").style.setProperty('padding-top', '10px', 'important');
I resolve similar problem with:
document.getElementById("xyz").style.padding = "10px 0 0 0";
Hope that helps.
Assuming you have HTML like this:
<div id='thediv'></div>
If you want to modify the style attribute of this div, you'd use
document.getElementById('thediv').style.[ATTRIBUTE] = '[VALUE]'
Replace [ATTRIBUTE] with the style attribute you want. Remember to remove '-' and make the following letter uppercase.
Examples
document.getElementById('thediv').style.display = 'none'; //changes the display
document.getElementById('thediv').style.paddingLeft = 'none'; //removes padding
document.getElementById("xyz").style.padding-top = '10px';
will be
document.getElementById("xyz").style["paddingTop"] = '10px';
I would recommend using a function, which accepts the element id and an object containing the CSS properties, to handle this. This way you write multiple styles at once and use standard CSS property syntax.
//function to handle multiple styles
function setStyle(elId, propertyObject) {
var el = document.getElementById(elId);
for (var property in propertyObject) {
el.style[property] = propertyObject[property];
}
}
setStyle('xyz', {'padding-top': '10px'});
Better still you could store the styles in a variable, which will make for much easier property management e.g.
var xyzStyles = {'padding-top':'10px'}
setStyle('xyz', xyzStyles);
Hope that helps
Surprised that I did not see the below query selector way solution,
document.querySelector('#xyz').style.paddingTop = "10px"
CSSStyleDeclaration solutions, an example of the accepted answer
document.getElementById('xyz').style.paddingTop = "10px";
document.getElementById("xyz").setAttribute('style','padding-top:10px');
would also do the job.
document.getElementById('id').style = 'left: 55%; z-index: 999; overflow: hidden; width: 0px; height: 0px; opacity: 0; display: none;';
works for me
I change css style in Javascript function.
But Uncaught TypeError: bild is null .
If I run it in a normal html file it work.
CODE:
var text = document.getElementById("text");
var bild = document.getElementById("bild");
var container = document.getElementById("container");
bild.style["background-image"] = "url('stock-bild-portrait-of-confident-senior-business-woman-standing-in-office-with-her-arms-crossed-mature-female-1156978234.jpg')";
//bild.style.background-image = "url('stock-bild-portrait-of-confident-senior-business-woman-standing-in-office-with-her-arms-crossed-mature-female-1156978234.jpg')";
// bild.style["background-image"] = "url('" + defaultpic + "')";
alert (bild.style["background-image"]) ;
bild.style["background-size"] = "300px";
bild.style["background-repeat"] = "no-repeat";
bild.style["background-position"] = "center";
bild.style["border-radius"] = "50%";
bild.style["background-clip"] = "border-box";
bild.style["transition"] = "background-size 0.2s";
bild.style["transition-timing-function"] = "cubic-bezier(.07,1.41,.82,1.41)";
bild.style["display"] = "block";
bild.style["width"] = "100px";
bild.style["height"] = "100px";
bild.style["text-decoration"] = "none";
bild.style["cursor"] = "pointer";
bild.style["overflow"] = "hidden";
bild.style["text-indent"] = "100%";
bild.style["white-space"] = "nowrap";
container.style["position"] = "relative";
container.style["font-family"] = "Arial";
text.style["position"] = "center";
text.style["bottom"] = "5px";
text.style["left"] = "1px";
text.style["color"] = "white";
newNode = document.createElement("span");
newNode.innerHTML = "text";
range.insertNode(newNode);
Is it possible to make the text in innerHTML with red background color? I want to add style="background-color:red" to just created span. Is it possible? Or it must have some id, and then I can change this span with jQuery?
Simple enough:-
newNode.style.backgroundColor = "red";
Better to give a classname for the span
<style>
.spanClass { background-color: red; }
</style>
newNode.className = "spanClass";
This worked for me:
var spanTag1 = document.createElement('span');
spanTag1.innerHTML = '<span style="color:red">text</span>';
OR
add class using js and set css to that class
var spanTag1 = document.createElement('span');
spanTag1.className = "mystyle";
Now set style to that class
<style>
.mystyle {
color:red;
}
</style>
You can add attributes directly to the DOM object. The style attribute can be assigned by this way too. Example:
var span = document.createElement("span");
span.setAttribute("style","color:white;background-color:red;");
var text = document.createTextNode("My text");
span.appendChild(text);
Of course you have to add this element created to their parent object in your page:
var parent = document.getElementById("parentObject");
parent.appendChild(span);
This method "setAttribute()" lets you to add other non-standard attributes used by animations and custom jquery options to your HTML standard tags.