How to Dynamically Change the Style Tag Using JavaScript

Changing element style attribute dynamically using JavaScript

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...

How to dynamically change the style tag using JavaScript?

You are probably trying to add css to the style tag. This can be accomplished using:

document.getElementsByTagName('style')[0].innerHTML=""; //some css goes here

You can also use:

document.styleSheets[0].cssText = ""; //some css goes here

How to dynamically change CSS style attribute of DIV tag?

var div = document.getElementById('div1');

// Clear Value
div.setAttribute('style','');
// OR
div.removeAttribute('style');

// Set Style / Append Style
div.style.backgroundColor = '#ff0000';

Don't modify the style attribute directly when adding or changing styles unless you want to remove them all.

JavaScript removeAttribute: https://developer.mozilla.org/en-US/docs/Web/API/Element.removeAttribute
Javascript Style: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style

How to create a style tag with Javascript?

Try adding the style element to the head rather than the body.

This was tested in IE (7-9), Firefox, Opera and Chrome:

var css = 'h1 { background: red; }',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');

head.appendChild(style);

style.type = 'text/css';
if (style.styleSheet){
// This is required for IE8 and below.
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}

How can I use a dynamic select form to change style in HTML and JavaScript?

Here's your code solution.

  1. If you want to add onchange function you need to use setAttribute function to add onchange function on selectbox in q3_func().
  2. You didn't defined any list veriable in changeBackground function that you want to use in that function event that you're getting colors parameter and you can use colors.options and colors.selectIndex
  3. You can't use document.p directly because p is not defined as veriable or it's not a document but it's a part of document. You can use document.getElementsByTagName('p')[0] [0] indecate index of tags.
    For example:

Your are using p tag 5 time in body [0] indecates first p tag and [1] indecates to 2nd.

<!DOCTYPE html>
<html lang="en">

<head>
<title>The Bridge of Death!!!</title>
<meta charset="UTF-8">
</head>

<body>
<h1>You Approach the Bridge of Death</h1>
<button id="q1button" onclick="q1_func()">Talk to Tim </button>
<p id="question_1"></p>
<p id="response_1"></p>

<script>
function q1_func() {
const name = prompt("What is your Name", "Arthur, King of the Britains");
if (name != null) {
document.getElementById("question_1").innerHTML = "What is Your Name?";
document.getElementById("response_1").innerHTML = "My name is " + name;
document.getElementById("q1button").remove();
q2_func();
}
}
</script>
<p id="question_2"></p>
<p id="response_2"></p>

<script>
function q2_func() {
var quest = prompt("What is your Quest", "To seek the Holy Grail!");
if (quest != null) {
document.getElementById("question_2").innerHTML = "What is Your Quest?";
document.getElementById("response_2").innerHTML = quest;
q3_func();
}
}
</script>

<p id="question_3"></p>
<p id="response_3"></p>
<script>
function changeBackground(colors) {
var val = colors.options[colors.selectedIndex].values;
document.getElementsByTagName('p')[0].style.backgroundColor = val;
}
</script>

<script>
function q3_func() {
var values = [" ", "blue", "red", "pink", "blue...no..."];
var select = document.createElement("select");
select.name = "colors";
select.id = "colors";
select.setAttribute("onchange", "changeBackground(this)");

for (const val of values) {
var option = document.createElement("option");
option.values = val;
option.text = val.charAt(0).toUpperCase() + val.slice(1);
select.appendChild(option);
}

var label = document.createElement("label");
label.innerHTML = "What is you favorite color?";
label.htmlFor = "color";

document.getElementById("question_3").appendChild(label).appendChild(select);
document.getElementById("q2_button").remove();
if (value === "blue...no...") {
alert("Ahhhhh!!!!! *Death* ");
};
}
</script>
</body>

</html>

Creating the dynamic style tag with the incrementing ID

I would advice you to use some other approach (using css like other people recommend here), but if you really want to try generate the styles manually then you can generate styles string (in the example using RegExp and placeholders) and then append it to head tag:

$array = {  "sections": {    "H": {      "name": "dummy",      "html": "<div id=\"dummy\"><h1>Some Title</h1><p>This is a para</p></div>"    }  }}
var defaultStyle = "#dummy--{id} {background-color: bisque;}#dummy--{id} H1 {color: {h1-color};font-size: 20px;}#dummy--{id} p{color: green;font-size: 15px;}"
$(function() { // counter which holds the counts of click var count = -1; $('#cm').click(function(event) { $htmlData = $array["sections"]["H"]['html']; // check the count value for second click if (++count > 0) // in case of not a first click parse the html and generate a jQuery object $htmlData = $($htmlData).attr('id', function(i, v) { // update the attrubute value return v + '--' + count // get back the html content from the DOM object })[0].outerHTML //$('#content').html($htmlData); $($htmlData).appendTo('#content').hide().slideDown(); var generated = defaultStyle.replace(/{id}/gi, count).replace(/{h1-color}/gi, count % 2 ? "red":"yellow"); $("<style type='text/css'>" + generated + "</style>").appendTo("head"); });})
#dummy {  background-color: bisque;}#dummy H1 {  color: blue;  font-size: 20px;}#dummy p {  color: green;  font-size: 15px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><button id="cm">Click me</button>
<ul id="content"> </ul>

Apply CSS dynamically with JavaScript

Using Jquery

Use the css() function to apply style to existing elements where you pass an object containing styles :

var styles = {
backgroundColor : "#ddd",
fontWeight: ""
};
$("#myId").css(styles);

You can also apply one style at the time with :

$("#myId").css("border-color", "#FFFFFF");

Vanilla JS :

var myDiv = document.getElementById("#myId");
myDiv.setAttribute("style", "border-color:#FFFFFF;");

With Css :

You can also use a separate css file containing the different styles needed inside classes, and depending on the context you add or remove those classes to your elements.

in your css file you can have classes like

.myClass {
background-color: red;
}

.myOtherClass {
background-color: blue;
}

Again using jquery, to add or remove a class to an element, you can use

$("#myDiv").addClass('myClass');

or

$("#myDiv").removeClass('myClass');

Again, you can also do the same with vanilla JS:

document.getElementById("#myId").classList.add('myClass') 

or

document.getElementById("#myId").classList.remove('myClass') 

I think this is a cleaner way as it separates your style from your logic. But if the values of your css depends from what is returned by the server, this solution might be difficult to apply.

Replace style tag with javascript equivalent

The answer was to use document.head.innerHTML += in an inline script block to add HTML representing the STYLE block and style. This is added to the DOM immediately after the SCRIPT tag that creates it. Using backticks for the HTML template containing the font size would have made it even easier, though in the end I had to support IE 11 so backticks were out.

The solution:

<script>
var fontSize = //font size retrieved here;
document.head.innerHTML += "<style type=\"text/css\"> \nbody { font-size: ".concat(fontSize, "em } \n</style>");
</script>


Related Topics



Leave a reply



Submit