2016-10-14 4 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> 

Имейте в виду, что я хочу использовать DOM только, не JQuery.

ответ

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>

Смежные вопросы