0

How to merge these two <ol> tags using javascript ?

Here is my code:

<ol id="myList1">
    <li>Apple</li>
    <li>Pear</li>
    <li>Peach</li>
</ol>
<ol id="myList2">
    <li>Orange</li>
</ol>

Output:

<ol id="myList1">
   <li>Apple</li>
   <li>Pear</li>
   <li>Peach</li>
   <li>Orange</li>
</ol>

Thanks in advance.

Parthiv
  • 828
  • 9
  • 20
  • 1
    How do you want to merge the tags? Do you want to create a new tag containing the children of both, or do you want to move the children into the first or last element? – Stuart P. Bentley Jun 30 '14 at 05:43

5 Answers5

1

Vanilla JS variant:

var list1    = document.getElementById('myList1'),
    list2    = document.getElementById('myList2'),
    children = list2.childNodes // select all children nodes from one element
    i, item;

// Add each children to list1
for (i = 0; item = children[i]; i++) {
    list1.appendChild(item);
}

// Remove list2 DOMElement
list2.parentNode.removeChild(list2);
rasmusx
  • 887
  • 8
  • 14
0
(function(){
  var otherLis = $("#myList2").find("li").detach(); // this will detach li's from second OL
  $("#myList1").append(otherLis); // this will appeend them to first OL
}())

DEMO

Jeetendra Chauhan
  • 1,977
  • 2
  • 15
  • 21
  • The OP didn't tag this post with jQuery, so I'm assuming a standard JS solution is preferred. Also, some explanation never hurts. – AstroCB Jun 30 '14 at 05:53
0

Try this in pure javascript:

var a = document.getElementById('myList1');
var b = document.getElementById('myList2');
a.innerHTML = a.innerHTML + b.innerHTML;
b.remove();

First get the list elements of both lists and then concatenate, and then add to the new list;

krg265
  • 383
  • 1
  • 10
  • atleast comment when you downvote how would i know my mistake – krg265 Jun 30 '14 at 06:04
  • Well, I'm not the one who down voted but I thought I'd mention that you forgot to remove the second `ol`. You can do `document.getElementById('myList2').remove();` in the end. – Fr0zenFyr Jun 30 '14 at 06:24
  • Yes I agree, but like I said, I'm not the one who down-voted your answer. Cheers! – Fr0zenFyr Jun 30 '14 at 06:46
  • krgaurav: Sorry for not leaving comment right away. My bad. The reason is that you should use native DOM manipulation methods not string concentration. – rasmusx Jul 01 '14 at 09:25
0

While not that elegant, there's a simple solution in pure JS:

document.getElementById("myList1").innerHTML += document.getElementById("myList2").innerHTML;

document.getElementById("myList2").remove();

It just takes adds the contents of myList2 to myList1 and removes myList2: not too much to explain there.

Demo

AstroCB
  • 12,337
  • 20
  • 57
  • 73
0

Try This:

document.querySelector('#myList1').appendChild(document.querySelector("#myList2>li"));

Fiddle

Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58