জাভাস্ক্রিপ্ট-এ insertBefore() মেথড দেওয়া আছে একটি নোডকে অন্য চাইল্ডের আগে চাইল্ড হিসেবে ইনসার্ট করতে। যদি ২টি লিস্ট থাকে, তবে আমরা আমাদের প্রয়োজন অনুযায়ী insertBefore() মেথড ব্যবহার করে এলিমেন্টগুলো শাফল করতে পারি।
সিনট্যাক্স
node.insertBefore(newnode, existingnode);
উদাহরণ-১
নিচের উদাহরণে, দুটি লিস্ট আছে এবং আমাদের প্রয়োজন অনুযায়ী লিস্টগুলো 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
উদাহরণ-২
<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