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.
Related
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>
I'm attempting to create a text element and then add CSS attributes
I've tried to use the code below
function create(text){
var t = document.createTextNode(text);
t.style.color = "black"
t.style.backgroundColor="white"
t.style.borderRadius="20px"
t.style.border="4px solid black"
document.body.appendChild(t);
}
create("hello");
I expect to create a text with a white background and 20px border radius with a 4px solid black border
Instead of a text node, which I don't think you can add styles to, just use a span instead
function create(text){
var t = document.createElement("span");
t.innerText = text;
t.style.color = "black"
t.style.backgroundColor="white"
t.style.borderRadius="20px"
t.style.border="4px solid black"
document.body.appendChild(t);
}
create("hello");
You are having trouble because text nodes are not meant to be styled.
You should create a DOM element instead. I took your code and update it in order to create a <p> (the nearest element of text node I guess) with your CSS:
function create(text) {
var t = document.createElement('p');
t.innerText = text;
t.style.color = "black"
t.style.backgroundColor="white"
t.style.borderRadius="20px"
t.style.border="4px solid black"
document.body.appendChild(t);
}
create("hello");
You are on the right direction. The only thing you need to do is change document.createTextNode(text) with:
var t = document.createElement('span');
t.innerText = text;
\\...
document.body.appendChild(t);
The reason why your code doesn't work is that you can only style HTML tags, and the the text node you created only contains the string you added, without a surrounding tag.
For example:
<span>
hello
</span>
is a tag with some text with it, while the hello text in the middle is a TextNode.
Hope this makes sense.
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode
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 am working on this example of appendChild() method.but the difference is here i am trying to add more text to a div dynamically.that was all right.but the hard part is the text i want to add will be red in color.how can i do that?
i tried
text.setAttributes('color',"red");
But it didn't work.so,how this task can be done??please help,thanks!!!!
the full code is given below............
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function create_text(){
var mydiv = document.getElementById("mydiv");
var text = document.createTextNode(" New text to add.");
mydiv.appendChild(text);
}
</script>
</head>
<body>
<button onclick="create_text();">Create Text Node</button>
<div id="mydiv">Welcome, here is some text.</div>
</body>
</html>
You would normally have to use CSS properties, however, text nodes cannot have CSS properties applied to them. You therefore need another container element:
You can choose any container element you wish, e.g. div, span, etc. It just needs to be capable of containing a text node. Having an element then allows us to access the styles property and set various styles (the color attribute in your case).
→ jsFiddle
function create_text(){
var mydiv = document.getElementById("mydiv");
var container = document.createElement("span");
var text = document.createTextNode(" New text to add.");
container.appendChild(text);
container.style.color = "red";
mydiv.appendChild(container);
}
Further note:
the order of the color assignments and calls of appendChild is arbitrary. The following would also be possible:
function create_text(){
var mydiv = document.getElementById("mydiv");
var container = document.createElement("span");
var text = document.createTextNode(" New text to add.");
container.appendChild(text);
mydiv.appendChild(container);
container.style.color = "red";
}
mydiv.style.color = 'red';
or just in css
#mydiv { color: red; }
if you have other elements inside the div that you don't want to be red, you'd need to wrap the new text in a span or div or another element before appending.
with jquery this would be super easy:
$('#mydiv').append('<span style="color:red">this is new text</span>');
If that's everything in your div, you could try
document.getElementById("mydiv").style.color="#ff0000";
I explain the problem by a simple example.
I have the following html page. It's simple.
There is one CSS Class named TestDiv and two javascript function.
addDiv creates new div and appends it to page by clicking on button "add new div".
setBlue is the function that i want to change the color of divs that has class TestDiv and I dont know how.
You can see that i wrote some code to change the current generated Divs inside the setBlue function. But I don't know how i can change the class to affect the new divs that will generated by addDiv function after that.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.TestDiv {
color:red;
}
</style>
<script>
function addDiv() {
var newDiv = document.createElement("div")
newDiv.className = "TestDiv";
newDiv.innerHTML = "test";
document.getElementById("firstDiv").insertBefore(newDiv);
}
function setBlue() {
var currentDivList=document.getElementsByClassName("TestDiv");
for(var i=0;i<currentDivList.length;i++){
currentDivList[i].style.color = "blue";
}
// What i can write here to change the TestDiv css class
// And after that, new (div)s will generate by new color(changed css class)
}
</script>
</head>
<body>
<div id="firstDiv" class="TestDiv">
test
</div>
<input type="button" value="add new div" onclick="addDiv();"/>
<input type="button" value="change color to blue" onclick="setBlue();"/>
</body>
</html>
I don't recommend adding or modifying CSS rules on-the-fly, but there are several solutions:
Modify the original CSS rule
<style id="myStyle">
.TestDiv {
color:red;
}
</style>
...
var myStyle = document.getElementById("myStyle");
myStyle.sheet.cssRules.item(0).cssText = ".TestDiv { color: blue }";
(I had to assign an ID to the style tag because I couldn't get it work in the jsFiddle environment otherwise. It should equally be possible by using document.styleSheets[0].)
Add a CSS rule to a newly created style sheet (thanks to pawel!)
var style = document.createElement('style');
document.head.appendChild(style);
style.sheet.addRule(".TestDiv", "color: blue");
Add raw CSS text to a newly created style sheet:
→ jsFiddle
var sheet = document.createElement('style')
sheet.innerHTML = ".TestDiv { color: blue }";
document.body.appendChild(sheet);
style.color creates an inline style that overrides the class styles. In order to retain whether setBlue() has been clicked store a var either isBlue = false or divClass = 'blue'/'red' and toggle a class on all the divs which retains your color styles:
http://jsbin.com/IdadUz/1/edit?html,css,js,output
You cannot directly modify style elements that have been created on the page or in external Style Sheets, one way to do this would be with the following javascript :
var newColor = '';
function addDiv() {
var newDiv = document.createElement("div")
newDiv.className = "TestDiv";
newDiv.innerHTML = "test";
document.getElementById("firstDiv").insertBefore(newDiv);
if (newColor != '') {
newDiv.style.color = newColor;
}
}
function setBlue() {
var currentDivList = document.getElementsByClassName("TestDiv");
for (var i = 0; i < currentDivList.length; i++) {
currentDivList[i].style.color = "blue";
}
newColor = 'blue';
}
When you click on the Change Color button it will set the newColor variable to blue. Then when you add a new div it will check if this variable has been set, if so it will change the style.
Example JSFiddle
I'd suggest adding a stylesheet to the head section:
function setBlue() {
var currentDivList=document.getElementsByClassName("TestDiv");
for (var i=0; i < currentDivList.length; i++) {
currentDivList[i].style.color = "blue";
}
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.innerHTML = ".TestDiv { color: blue; }";
head.appendChild(style);
}