CSS Won't Apply to Dynamically Created Elements
EDIT: Turns out a simple spelling mistake broke my code. Thanks for
everyone's input!
I'm using JavaScript to create HTML elements and adding them to the DOM.
I've tried setting the class attribute both through .setAttribute("class",
"...") and element.className = "..." and the CSS does not seem to apply to
those elements. I've tried moving around the position of the <link> tag
(that references my stylesheet), but all to no avail.
Here's my code that generates the HTML elements:
function build_login_box(anchor) {
anchor = document.getElementById(anchor);
var form = document.createElement("form");
form.id = "login_form";
form.setAttribute("onkeypress", "check_for_enter(event.keyCode, do_login);")
var user_box = document.createElement("input");
user_box.className = "loginsignupinput";
user_box.type = "text";
user_box.id = "user";
user_box.name = "user";
//user_box.setAttribute("style", "text-align: center; font-size:20px;
width:300px;");
var pass_box = document.createElement("input");
pass_box.type = "password";
pass_box.id = "pass";
pass_box.name = "pass";
pass_box.setAttribute("class", "loginsignupinput");
var log_button = document.createElement("input");
log_button.type = "button";
log_button.id = "login_button";
log_button.value = "Login";
log_button.setAttribute("onclick", "do_login();");
form.appendChild(user_box);
form.appendChild(document.createElement("br"));
form.appendChild(pass_box);
form.appendChild(document.createElement("br"));
form.appendChild(log_button);
anchor.appendChild(form);
}
And then this is how they're being added to the page:
<div id="signuplogin"><div id="login" class="loginforms"></div></div>
<script type="text/javascript">
build_login_box("login");
</script>
And the CSS in Question:
.loginforms {
margin-top:100px;
}
.loginsignupinput {
text-align:center;
font-size:20px;
width:300px;
}
If I uncomment the line in the JS function (and use inline styles), the
styles work just fine.
If it makes a difference to know, my javascript function is stored in a
separate .js file and the stylesheet is also a separate .css file. Thanks!
No comments:
Post a Comment