Is there any way to change CSS Class that registered in browser - javascript

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);
}

Related

How to dynamically add a CSS class and implement its style in JavaScript

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>

Javascript Function to Remove Div

I need a function that can delete the div one by one .
My code is shown below. in my code i have created a function to create a div when i click a button . and i can't figure how to delete div one by one .
Please help me with the correct code to delete div one by one.
<html>
<head>
</head>
<body>
<button id="buttonone" onclick="creatediv()">CREATE A DIV</button>
<button id="buttontwo" onlick="removedivider()">Remove DIV </button>
<script>
function creatediv()
{
document.getElementById("buttonone").innerHTML="CREATE ANOTHER DIV";
var newdiv = document.createElement("div");
newdiv.setAttribute("id","newdiv");
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
newdiv.appendChild(text);
newdiv.style.color="white";
newdiv.style.width="100px";
newdiv.style.backgroundColor="green";
document.body.appendChild(newdiv);
}
function removedivider()
{
//Function to Remove the DIV one by one;
}
</script>
</body>
</html>
<script>
var index = 0;
function creatediv()
{
++index;
document.getElementById("buttonone").innerHTML="CREATE ANOTHER DIV";
var newdiv = document.createElement("span");
newdiv.setAttribute("id","newdiv" + index);
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
newdiv.appendChild(text);
newdiv.style.color="white";
newdiv.style.width="100px";
newdiv.style.backgroundColor="green";
document.body.appendChild(newdiv);
}
function removedivider()
{
document.body.removeChild(document.getElementById("newdiv" + index));
--index;
}
</script>
Should work, I didn't test.
You weren't very clear regarding which div should be removed. Also, in your code, you repeatedly appended divs with the same id. You can't do that.
I made a quick example that removes the div appended first (a queue). I gave each date an id based on the current time, but such isn't really necessary. You could always just remove the first child of the parent div to which you are appending these divs.
However, if you plan on appending these divs in places that are not necessarily all under the same parent, then giving them unique ids and storing said ids is useful.
fiddle
HTML
<button id="add">add</button>
<button id="remove">remove</button>
<div id="holder">
<p>Added divs will go here</p>
</div>
JavaScript
var ids = [];
document.getElementById("add").onclick = function () {
var id = new Date().getTime(), // generate unique id (sort of)
div = document.createElement("div"); // create a div element
ids.push(id); // push the generated id to the holder array, ids
div.appendChild(document.createTextNode(id)); // append a text node to the div
div.setAttribute("class", "newDiv"); // give it a class for styling
div.setAttribute("id", id); // set its id
document.getElementById("holder").appendChild(div); // append the div
}
document.getElementById("remove").onclick = function () {
if (ids.length) { // only perform if a div has been appended
var div = document.getElementById(ids.shift());
// ids.shift() removes and returns ids[0], or the earliest added div
// this finds that element in the DOM
div.parentNode.removeChild(div); // and removes it
} else { // otherwise alert that there are no divs to remove
alert("no divs to remove!");
}
}
CSS
.newDiv {
height: 20px;
width: 110px;
background-color: #7EA8CA;
border: solid 1px #93CC76;
}
Replace your code with the following
<!DOCTYPE html>
<html>
<head>
<title>DIVs</title>
<script type="text/javascript">
function create_div() {
document.getElementById("button1").innerHTML="CREATE ANOTHER DIV";
var div = document.createElement("DIV");
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
div.appendChild(text);
div.style.color = "white";
div.style.width = "100px";
div.style.backgroundColor = "green";
document.body.appendChild(div);
}
function remove_div() {
var div = document.getElementsByTagName('DIV'), i;
for(i = div.length-1; i >= 0; i--){
div[i].parentNode.removeChild(div[i]);
return false;
}
}
</script>
</head>
<body>
<button id="button1" onclick="create_div()">CREATE DIV</button>
<button id="button2" onclick="remove_div()">REMOVE DIV</button>
</body>
</html>
By the way, you can't have multiple DIVs having the same ID. Check the working jsBin
This function assumes there will be no other div elements. It will also remove the divs in fifo order.
function removedivider() {
var divs = document.getElementsByTagName('div');
if (divs.length > 0) divs[0].remove();
}
EDIT:
Here's a jsfiddle

add color dynamically to added text

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";

adding css styles to dynamically added <form> elements in java script

I used the following code (Javascript) to dynamically load elements into "Mobile Webpage". It works fine but i can't set CSS styles(like height,width...) to those newly added elements.
here by this code buttons are loaded perfectly .
in this i am unable to vary the size of dynamically loaded button using css elements.
<head>
<script type="text/javascript">
var arrayToModify = [];
window.onload = function () {
var i, MyArray, ButtonContainer, NewButton;
MyArray = ["Option 1","Option 2","Option 3","Option 4","Option 5"];
ButtonContainer = document.getElementById("Button_holder");
for (i = 0; i < MyArray.length; i++) {
NewButton = document.createElement('input');
NewButton.type = 'button';
NewButton.value = MyArray[i];
NewButton.id = MyArray[i];;
NewButton.onclick = function () {
alert('You Clicked '+this.id);
arrayToModify[arrayToModify.length] = this.id;
};
ButtonContainer.appendChild(NewButton);
}
};
</script>
<style>
NewButton
{
width:100%;
height:120px;
background-color:red;
}
ButtonContainer
{
width:100%;
height:120px;
background-color:yellow;
}
.divclass
{
height:400px;
background-color:lightblue;
}
</style>
</head>
<body>
<div id="Button_holder" class="divclass">
</div>
<input type='button' onclick='alert(arrayToModify);' class="ntl" value='Vote' />
</body>
</html>
Your CSS is wrong. CSS doesn't look at JS variable names. So your CSS selectors are looking for those HTML tags (i.e. an HTML tag <NewButton>, which obviously doesn't exist).
Instead, try adding a class to each of your new inputs and button container, and then prefix your CSS selectors with a . (which is a class selector).
Here is an example: jsFiddle Demo
HTML:
<div id="Button_holder" class="divclass ButtonContainer"> <!-- added a class name here -->
</div>
<input type='button' onclick='alert(arrayToModify);' class="ntl" value='Vote' />
CSS:
.NewButton
{
width:100%;
height:120px;
background-color:red;
}
.ButtonContainer
{
width:100%;
height:120px;
background-color:yellow;
}
.divclass
{
height:400px;
background-color:lightblue;
}
JS:
var arrayToModify = [];
window.onload = function () {
var i, MyArray, ButtonContainer, NewButton;
MyArray = ["Option 1","Option 2","Option 3","Option 4","Option 5"];
ButtonContainer = document.getElementById("Button_holder");
for (i = 0; i < MyArray.length; i++) {
NewButton = document.createElement('input');
NewButton.type = 'button';
NewButton.value = MyArray[i];
NewButton.id = MyArray[i];
NewButton.className = 'NewButton'; // added a class name here
NewButton.onclick = function () {
alert('You Clicked '+this.id);
arrayToModify[arrayToModify.length] = this.id;
};
ButtonContainer.appendChild(NewButton);
}
};
And, as #SurrealDreams said, it would be a good idea to keep your CSS in an external file to make it easier to maintain and reuse. Suppose you had multiple pages with the exact same styles? Instead of rewriting these styles every time, just put them in an external .css file and then include that file in your <head> using something like <link rel="stylesheet" type="text/css" href="path/to/your/css/file.css" />.
I would really suggest you go through a CSS tutorial. For this specific problem, this section should prove useful.
What are NewButton and ButtonContainer in css? It looks written as tags. If you need those as classes, you should set . before each, e.g. .NewButton.
Updated code:
<head>
<script type="text/javascript">
var arrayToModify = [];
window.onload = function () {
var i, MyArray, ButtonContainer, NewButton;
MyArray = ["Option 1","Option 2","Option 3","Option 4","Option 5"];
ButtonContainer = document.getElementById("Button_holder");
for (i = 0; i < MyArray.length; i++) {
NewButton = document.createElement('input');
NewButton.type = 'button';
NewButton.value = MyArray[i];
NewButton.className = 'NewButton';
NewButton.id = MyArray[i];;
NewButton.onclick = function () {
alert('You Clicked '+this.id);
arrayToModify[arrayToModify.length] = this.id;
};
ButtonContainer.appendChild(NewButton);
}
};
</script>
<style>
.NewButton
{
width:100%;
height:120px;
background-color:red;
}
.ButtonContainer
{
width:100%;
height:120px;
background-color:yellow;
}
.divclass
{
height:auto;
background-color:lightblue;
}
</style>
</head>
<body>
<div id="Button_holder" class="divclass">
</div>
<input type='button' onclick='alert(arrayToModify);' class="ntl" value='Vote' />
</body>
</html>
Your approach has been to assign CSS styles to the names of JavaScript variables/objects. There's no direct connection between the two - CSS is looking for HTML elements with tags named ButtonContainer and NewButton. CSS isn't "smart" - it's not going to map the HTML generated by JavaScript to the styles. It's looking for a simple match, so you need to design the code so it has a match.
To answer your question as asked, you could include a line like this...
NewButton.style = "width: 20px; height: 40px; border: 1px solid #000;";
This will set styles on each generated NewButton element. Using CSS classes will give you a better overall result.
Please note - there's a better approach.
In general, the best approach is to create your code with classes and ids as part of the code. Include CSS rules in your general CSS files to style those elements.
While you can add style to generated code, it's best to keep all your styling in the CSS files. It's much easier to maintain that way. It's all in one place, and a typo won't break your scripts. CSS is much more tolerant of errors. Inline styles are best avoided, just like it's best to avoid JavaScript written inside HTML elements.
In Javascript, you can add css Class like this:
For instance:
document.getElementById("your-ID").setAttribute("class", "your-className");
Try like this.
EDIT: As Travesty3 mentioned you're missing the add . for class selector in css. Once you correct mistake, you can use the above approach to add the classes.
ButtonContainer.setAttribute("class", "ButtonContainer");
NewButton.setAttribute("class", "NewButton");
Add the above two lines at the last of your JS code. check this Updated JSFiddle in this I've reduced the remove the height and width of the button to show difference.

JavaScript: how to change CSS style of created span?

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.

Categories

Resources