Reputation: 7969
I have a variable which contains 3 tag names which are separated from each other by a "," character. I want to split them appart with .split() function and then create and append 3 elements to the document body.
<head>
<style>
div { height:500px; width:500px; background:#F00; float:left}
span{display:block; float:right}
</style>
<script type="text/javascript">
var element= div,p,span;
var j=element.split(',')
for(i=0;i<j.length;i++){
var crt=document.createElement(j[i])
}
document.body.append(crt)
</script>
</head>
<body>
</body>
Upvotes: 2
Views: 8035
Reputation: 35793
Your 'element' variable needs to be a string. You need to use appendChild() rather than append(), and the appendChild() call should be inside your loop:
var element = "div,p,span";
var j = element.split(',');
var crt;
for(var i = 0; i < j.length; i++) {
crt = document.createElement(j[i]);
document.body.appendChild(crt);
}
http://jsfiddle.net/infernalbadger/wEBqY/1
Upvotes: 5
Reputation: 25332
var tags = "div,p,span".split(",");
for (var i=0, tag; tag = tags[i++];)
document.body.appendChild(document.createElement(tag));
However, the body
tag is not parsed yet by the browser when you're executing this code, so you should put this code after the <body>
or run it when the DOM is loaded (onload
event or DOMContentLoaded
if supported).
You could also use forEach where is supported (ES5, there are plenty of shims, also in the MDN page I linked):
var tags = "div,p,span".split(",");
tags.forEach(function(tag) {
document.body.appendChild(document.createElement(tag));
});
Or if you're using any support library (jquery, underscore, etc) they provide equivalent function.
Upvotes: 0
Reputation: 178384
What the others said PLUS you need to do this onload DEMO:
<head>
<style>
div { height:500px; width:500px; background:#F00; float:left}
span{display:block; float:right}
</style>
<script type="text/javascript">
var elements= ["div","p","span"];
window.onload=function() {
for(var crt,i=0, n=elements.length;i<n;i++){
crt=document.createElement(elements[i])
document.body.appendChild(crt)
}
}
</script>
</head>
<body>
</body>
Upvotes: 1
Reputation: 9034
Try this
for(i=0; i<j.length; i++)
{
var crt = document.createElement(j[i]);
document.body.append(crt);
}
Upvotes: 1
Reputation: 12415
This code seems well, except 2 points:
var element = div,p,span
is not a valid statement, you shoudl wrap quote (") to create a string: var element = 'div,p,span';
You should put the statement document.body.append(crt)
in your for
loop so that each element would be append to <body>
.
Upvotes: 1