简体   繁体   中英

Applying css to a javascript variable

I want to add color and border to a javascript variable using css. Below is my code;

var msg = "OK"; //i want this to colored and bordered with green.
msg = "Conflict"; // i want this to be colored and bordered with red.

I tried another answer from other questions but it doesn't seem to work with me.

You can't add CSS to a javascript variable.

if you are create element using javascript

html:

<div class="parent-div">

</div>

js:

var msg = "OK";
element = document.createElement('p');

// Give the new element some content and css
element.innerHTML = msg;
element.style.color = 'green';
element.style.border = "1px solid red";

// append element to parent div
document.querySelector('.parent-div').appendChild(element);

Just do without javascript

html:

<div class="parent-div">
  <p class="child-one">OK</p>
  <p class="child-two">Conflict</p>
</div>

css:

.parent-div .child-one {
  color: red;
  border: 1px solid green;
}

.parent-div .child-two {
  color: green;
  border: 1px solid red;
}

If you're just trying to add styles to a JavaScript variable you can't do that, and I don't understand what you would hope to achieve by doing that.

I am therefore going to assume you want to add styles to an html element that you have extracted as a JavaScript variable like so

let msgElement = document.getElementById('msg')
let msg = "OK"
msgElement.innerHTML = msg

In this case, you can add styles to the element like so

msgElement.style.color = "red"
msgElement.style.border = "2px solid red"

In your example, when you change the value of msg to "Conflict", you are doing just that - changing it. You can't have two separate values held by the same variable.

As one of the comments says, this is basic web development, so I would advise some further reading, or an online course such as those provided by Codeacademy

As the other answers state, you can't apply a CSS rule to a variable. You can, however, do something like this:

<html>
<head>
<style>
.redgreen {border-style: solid; border-color: green; color: red;}
</style>
<script>
function foo() {
    let msg = "<div class='redgreen'>Hello, world!</div>";
    document.getElementById("themsg").innerHTML = msg;
    }
</script>
</head>
<body onload='foo();'>
<p id='themsg'>Your message here</p>
</body>
</html>

That is, define "msg" as an HTML element instead of a text string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM