Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Can you add CSS after you have added an Element

I was wondering if you can add some CSS after you have added in some text to your document through JavaScript?

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>


    <!-- <script type="text/javascript" src="javascript_review.js"></script> -->
    <script type="text/javascript" src="js_review_login.js"></script>
</body>
</html>
//get the username and password from user
var userName = prompt("Username: ");
var passWord = prompt("Password: ");


//if the username is a admin
if ( userName.toUpperCase() === "ADMIN" && passWord.toUpperCase() === "PASSWORD") {
    document.write("<h1>Welcome Admin!</h1>");
    adminRun();
} else if ( userName.toUpperCase() === "GUEST" && passWord.toUpperCase() === "JS") {
    document.write("<h1>Welcome User!</h1>");
    userRun();
} else {
    alert("User Unknown!! ALERT!!");
};


function adminRun() {
    document.write("<h3>These are the setting that an admin have.</h3>");
    document.write("<p>1: Change the network configuration.</p>");
    document.write("<p>2: Change the password.</p>");
    document.write("<p>3: Change the boss's password.</p>");
    document.getElementsByTagName("h3").style.color="red";
};

function userRun() {
    document.write("These are the setting that an admin have.");
    document.write("1: Change the personal configuration.");
    document.write("2: Change the password.");
    document.write("3: Change the background image.");
};

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

Yes. Your format is not quite correct. getElementsByTagName return a HTMLCollection of elements. To set the color of the first item, add then index [0]:

document.getElementsByTagName('h3')[0].style.color="red";

For more elements you can loop over the collection of elements:

for ( var i = 0; i < document.getElementsByTagName('h3').length; i +=1 ) {
  document.getElementsByTagName('h3')[i].style.color="red";
};

You could also consider using the setAttribute method (http://www.w3schools.com/jsref/met_element_setattribute.asp) to add a class to these elements. This would allow you to "pre-write" the CSS you wanted to use in a class, and then add the class to the elements at the appropriate time.