I have a trouble while split page by Javascript. I want to move 17 p tags into one div tag.
So I have 34 p tags like this:
<p>1</p> <!-- Each p tag have the value is the number of the p tag -->
And then I have this Javascript code:
var p = document.getElementsByTagName("p");
var div = document.createElement("div");
for(i=0;i<17;i++){
div.appendChild(p[i]);
}
document.getElementsByTagName("body")[0].appendChild(div);
And the result I received is in the div tag, there are 17 p tags but the value of these p tag is odd number, which mean like this:
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
This is the demo: http://jsbin.com/eyivic
Meantime, I want the p tags in the div tag will look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
So what is the problem? How can I fix it?
Thanks you so much!
When you make an
appendChildon the div, it removes the element of yourparray. This will make this “only odds” behaviour happens. Let’s say that you have 4 p elements.If you make an
appendChildfromp[0]it will move your p element as you expected, but now your list is like this:You are now pointing to
p[1], that you were expecting that was the element 2, but it will be the element 3 instead.To fix it you can always point to
p[0]and it will behave as you expect.