2016-10-14 7 views
0

새 요소 (div)를 만들고 싶지만 마지막 요소로 만드는 대신 두 요소 사이에 만들고 싶습니다. 내가하고 싶은 간단한 코드를 만들었습니다.DOM - HTML 요소를 이동하는 방법?

<!DOCTYPE html> 
<html lang="ca"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Document</title> 
    <script> 
    function createDiv() { 
     var newDiv = document.createElement("div"); 
     var txt = document.createTextNode("I'm the second div"); 
     newDiv.appendChild(txt); 

     document.body.appendChild(newDiv); 
    } 
    </script> 
</head> 
<body> 
    <div class="first"> 
    <p>I'm the first div</p> 
    </div> 

    <div class="third"> 
    <p>I'm the third div</p> 
    </div> 
    <button type="button" name="button" onclick="createDiv()">Create the second Div</button> 
</body> 
</html> 

jQuery가 아니라 DOM 만 사용하고 싶습니다.

답변

0

당신은 세 번째 div

function createDiv() { 
 
     var newDiv = document.createElement("div"); 
 
     var txt = document.createTextNode("I'm the second div"); 
 
     newDiv.appendChild(txt); 
 
     var thirdDiv = document.getElementById("thrid"); 
 
     thirdDiv.parentNode.insertBefore(newDiv, thirdDiv); 
 
    }
<!DOCTYPE html> 
 
<html lang="ca"> 
 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title>Document</title> 
 
</head> 
 
<body> 
 
    <div class="first"> 
 
    <p>I'm the first div</p> 
 
    </div> 
 
    <div id="thrid" class="third"> 
 
    <p>I'm the third div</p> 
 
    </div> 
 
    <button type="button" name="button" onclick="createDiv()">Create the second Div</button> 
 
</body> 
 
</html>

전에 삽입하여 다음을 수행 할 수 있습니다
관련 문제