자바스크립트 insertBefore()를 제공했습니다. 노드를 다른 자식보다 먼저 자식으로 삽입하는 방법입니다. 2개의 목록이 있는 경우 insertBefore() 메서드를 사용하여 요구 사항에 따라 요소를 섞을 수 있습니다. .
구문
node.insertBefore(newnode, existingnode);
예시-1
다음 예에는 두 개의 목록이 있으며 요구 사항에 따라 insertBefore() 를 사용하여 목록을 섞었습니다. 방법. 액세스 목록에 있는 여러 요소의 색인을 사용할 수 있습니다.
<html>
<body>
<ul id="List1"> <li>Tesla </li><li>Solarcity </li> </ul>
<ul id="List2"> <li>Google </li> <li>Drupal </li> </ul>
<script>
var node = document.getElementById("List2").firstChild;
var list = document.getElementById("List1");
list.insertBefore(node, list.childNodes[1]);
</script>
</body>
</html> 출력
Tesla Google Solarcity Drupal
예시-2
<html>
<body>
<ul id="List1"> <li>Tesla </li> <li>Solarcity </li> </ul>
<ul id="List2"> <li>Google </li> <li>Drupal </li> </ul>
<script>
var node = document.getElementById("List2").firstChild;
var list = document.getElementById("List1");
list.insertBefore(node, list.childNodes[0]);
</script>
</body>
</html> 출력
Google Tesla Solarcity Drupal