why the color of the label doesn't change?
After the page l开发者_StackOverflow中文版oads the color of the label (which is "enter your name") should change to red.But the color of the label remains the same.Why is this so ?
SCRIPT
window.onload = startScript;
function startScript() {
if( document.getElementById("text_field").value === "me") {
var allTags = document.getElementsByTagName("label");
allTags.className = "inserter";
}
}
HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="inserter.js">
</script>
<style type="text/css">
@import url("inserter.css");
</style>
</head>
<body bgcolor="#99FFFF">
<form>
<label>Enter your name<input type="text" id="text_field" value="me" />
</label>
</form>
</body>
</html>
CSS
@charset "utf-8";
/* CSS Document */
.inserter {
color:#F00;
}
Now since the value is equal to me
class name "inserter" is dynamically inserted to the label element and the color should appear to be red.
Why doesn't this happen ?
I think you need to loop through allTags
:
var allTags = document.getElementsByTagName("label");
for (var i = 0; i < allTags.length; i++) {
allTags[i].className = 'inserter';
}
If you can though use jQuery, it makes life so much easier!
UPDATE to add jQuery equivalent of your code:
if ($('#text_field').val() === 'me') {
$('label').addClass('inserter');
}
It's just so much tidier
The getElementsByTagName
method returns an array containing each of the DOM elements that match that tag. Calling allTags.className = 'inserter'
assigns a value to the 'className' property of the array itself, not to each of the elements within that array. You'll need to iterate through it, and assign the className to each tag individually.
As others have already mentioned getElementsByTagName() returns an array with elements but also you should add brackets to the first row where you call startScript() to identify it as a function.
This example works; http://jsfiddle.net/aQASU/
Try this through jquery.
allTags.addClass("inserter");
精彩评论