<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
如何使用 Javascript 交换 Div 的位置? HTML 文档中也应该更改它吗?
喜欢:
<div>7</div>
<div>5</div>
<div>1</div>
<div>4</div>
<div>2</div>
<div>6</div>
<div>3</div>
它应该像这样更改并且也应该保存在 HTML 文档中
最佳答案
这是解决问题的最简单方法。 将外部 div 的/节点视为容器或内容将被替换的位置。 (您不必替换 div,但必须替换其内容。)
function replaceContent(x, z){
// save the inner html of the first node in temp
let temp = document.getElementById(x).innerHTML;
// move the innerHtml of the second node into first node
document.getElementById(x).innerHTML = document.getElementById(z).innerHTML;
// replace the second node's inner html with temp (saved previously)
document.getElementById(z).innerHTML = temp;
}
// replace the divs of id 2 and 4
replaceContent("2", "4");
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
<div id="4">4</div>
关于javascript - 如何使用javascript交换html div元素位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60905317/