[ACCEPTED]-set html text color and size using javascript-html
var elem = document.getElementById("MonitorInformation");
elem.innerHTML = "Setting different HTML content";
elem.style.color = "Red";
elem.style.fontSize = "large";
0
var myDiv = document.getElementById("MonitorInformation");
myDiv.style.fontSize = "11px";
myDiv.style.color = "blue";
Take a look at the JavaScript Style Attributes
0
I've abstracted a few methods, which could 8 make them a little more useful for multiple 7 invocations:
var el = document.getElementById("MonitorInformation");
function text( el, str ) {
if ( el.textContent ) {
el.textContent = str;
} else {
el.innerText = str;
}
}
function size ( el, str ) {
el.style.fontSize = str;
}
function color ( el, str ) {
el.style.color = str;
}
size( el, '11px')
color( el, 'red' )
text(el, 'Hello World')
Note: The best practice to dynamically 6 change this type of stuff would be by setting 5 the styles in a seperate external selector:
.message 4 { color:red; font-size:1.1em; }
And toggling 3 the class name, .className+= 'message' ( or 2 an abstracted function to add/remove classes 1 ).
$("#MonitorInformation").text("Hello everyone").css("color", "red")
0
One of the easiest ways is to use a library 6 like jQuery. This handles all the differences 5 in browser JavaScript implementations for 4 you and gives you a nice, easy API to program 3 against.
Add a reference to jQuery using 2 the following code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
Then you can get a reference 1 to your element and modify it as follows:
$("#MonitorInformation").css('font-size', '2em').css('color', '#FF0000');
Assuming your style values are not computed 8 in the JS, there are two seperate ways parts 7 to this:
- Presentation is best handled by CSS, so set up a style-rule using a class that contains the information about how you want the element to look.
- On the elements that you want to have the appearance, use Javascript to change the class attribute to match the class in your CSS.
This has the benefits of making 6 the JS easy - you only need to change one 5 attribute (the class attribute is referenced 4 with element.className
in JS as 'class' is a reserved word). And 3 that all the styling information is contained 2 in one CSS file where it's easy to compare 1 to the other styles and make changes.
document.getElementById("MonitorInformation").innerHTML = "some text";
document.getElementById("MonitorInformation").style.color = "green";
0
const Monitorinfo = document.queryselector('MonitorInformation');
Monitorinfo.style.color = 'red';
Monitorinfo.style.fontSize = '20px';
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.