Test for createAttribute vs. setting the attribute
When creating DOM elements dynamically, we can use createAttribute then setting nodeValue, or skipping that and just setting the attribute. This is a test to see in which browsers (or if) that fails.
by DonamiteIsTNT
October 06, 2011
HTML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>createAttribute() vs. setting attributes</title>
<style>
.window, .result {
border:1px solid #CCC;
float:left;
width:40%;
padding:100px 2.5%;
text-align:center;
}
.result:first-child {
clear:both;
}
.result {
float:left;
padding:1em 2.5%;
}
.error {
color:red;
}
.success {
color:#03F;
font-weight:bold;
}
</style>
</head>
<body>
<div id="createWin" class="window"><u>createAttribute()</u><br><br><br>Input: </div>
<div id="setWin" class="window"><u>Setting the attribute</u><br><br><br>Input: </div>
<div id="createRes" class="result error">ERROR</div>
<div id="setRes" class="result error">ERROR</div>
</body>
</html>
JavaScript
function usingCreate() {
var input = document.createElement("input"),
type = document.createAttribute("type"),
name = document.createAttribute("name"),
maxlength = document.createAttribute("maxlength");
type.nodeValue = "text";
name.nodeValue = "username";
maxlength.nodeValue = "10";
input.setAttributeNode(type);
input.setAttributeNode(name);
input.setAttributeNode(maxlength);
createWin.appendChild(input);
createRes.innerHTML = "No JS errors";
createRes.className = "result success";
}
function usingSet() {
var input = document.createElement("input");
input.type = "text";
input.name = "username";
input.maxLength = "10";
setWin.appendChild(input);
setRes.innerHTML = "No JS errors";
setRes.className = "result success";
}
var createWin = document.getElementById("createWin"),
setWin = document.getElementById("setWin"),
createRes = document.getElementById("createRes"),
setRes = document.getElementById("setRes");
usingCreate();
usingSet();