사용자 도구

사이트 도구


wiki:javascript:javascript_note:insertbefore

Javascript HTML DOM insertBefore() Method

  • description : Javascript HTML DOM insertBefore() Method
  • author : 오션
  • email : shlim@repia.com
  • lastupdate : 2021-06-03


The source of the article

Example

<ul> 요소의 첫 번째 자식 요소 앞에 새로운 <li> 요소를 삽입합니다.

<body>
 
  <ul id="myList">
    <li>Coffee</li>
    <li>Tea</li>
  </ul>
 
  <p>Click the button to insert an item to the list.</p>
 
  <button onclick="myFunction()">Try it</button>
 
  <p><strong>Example explained</strong><br>First create a LI mode, 
  <br>then create a Text node, <br> then append the Text nodeto the LI node. 
  <br>Finally insert the LI node before the first child node in the list.</p>
 
  <script>
    function myFunction() {
      var newItem = document.createElement("LI");/* Create a <li> node */
      var textnode = document.createTextNode("Water");/* Create a text node */
      newItem.appendChild(textnode);/* Append the text to <li> */
 
      var list = document.getElementById("myList");/* Get the <ul> element to insert a new node */
      list.insertBefore(newItem, list.childNodes[0]);/* Insert <li> before the first child of <ul> */
    }
  </script>
 
</body>

Definition and Usage

insertBefore() 메서드는 지정한 기존 자식 요소 바로 앞에, 노드를 자식 요소로 삽입합니다.

Tip: 텍스트가 있는 새 목록 항목을 만들려면, <li> 요소에 덧붙이는 텍스트 노드로 텍스트를 만든 다음,
<li>를 목록에 삽입해야 합니다.

insertBefore 메서드를 사용하여 기존 요소를 삽입/이동할 수도 있습니다( “More Examples”참조)

Syntax

node.insertBefore(newnode, existingnode)

Parameter Values

Parameter Type Description
newnode Node object 필수입니다. 삽입하려는 노드 객체
existingnode Node object 필수입니다. 새로운 노드를 삽입하려는 곳의 아래에 있는 기존의 자식 노드.
null로 설정되면, insertBefore는 끝에 새 노드를 삽입합니다.

Technical Details

Return Value : 노드 객체이며, 삽입된 노드를 나타냅니다.

More Examples

Example

한 목록에서 다른 목록으로 <li> 요소를 이동합니다:

<body>
 
  <ul id="myList1">
    <li>Coffee</li>
    <li>Tea</li>
  </ul>
 
  <ul id="myList2">
    <li>Water</li>
    <li>Milk</li>
  </ul>
 
  <p>Click the button to move an item from one list to another</p>
 
  <button onclick="myFunction()">Try it</button>
 
  <script>
    function myFunction() {
      var node = document.getElementById("myList2").lastChild;/* Milk */
      var list = document.getElementById("myList1");
      list.insertBefore(node, list.childNodes[0]);/* Milk를 myList1의 인텍스 0의 앞에 삽입 */
    }
  </script>
 
</body>
/var/services/web/dokuwiki/data/pages/wiki/javascript/javascript_note/insertbefore.txt · 마지막으로 수정됨: 2023/01/13 18:44 (바깥 편집)