我想在其上方具有相同类名的上一个div之前插入一个类名为“ section”的div。
这是div层级
第(1)节->第(2)节->第(3)节
我想将带有类名部分的div移动到第三个带有类名部分的div之前。我想动态地执行此操作,我想对其他div进行相同操作,将它们移至具有相同类的上一个或下一个div之前或之后。
使用jquery的最佳方法是什么?
答案 0 :(得分:2)
您甚至可能不需要jQuery,您可以使用Node.insertBefore()
,NonDocumentTypeChildNode.previousElementSibling
和Node.parentElement
使用普通的JS:
document.getElementById('move').onclick = () => {
const sections = document.getElementsByClassName('section');
const lastSection = sections[sections.length - 1];
const sectionBeforeLastSection = lastSection.previousElementSibling;
// Insert lastSection before sectionBeforeLastSection.
// Note insertBefore is called on the parent element, thus the
// lastSection.parentElement.
lastSection.parentElement.insertBefore(lastSection, sectionBeforeLastSection);
};
.section {
border: 3px solid black;
height: 30px;
margin: 0 0 10px;
}
.a { background: red; }
.b { background: yellow; }
.c { background: cyan; }
#move {
border: 3px solid black;
background: none;
padding: 10px 15px;
font-family: monospace;
}
<div class="section a"></div>
<div class="section b "></div>
<div class="section c"></div>
<button id="move">MOVE LAST ONE UP</button>
对这些方法的支持很好,您可能不需要支持较旧的浏览器,但是您也可以使用Node.replaceChild()
和Node.appendChild()
以不太直观的方式做到这一点,它们的效果也稍好一些支持:
document.getElementById('move').onclick = () => {
const sections = document.getElementsByClassName('section');
const lastSection = sections[sections.length - 1];
const sectionBeforeLastSection = sections[sections.length - 2];
// Replace sectionBeforeLastSection with lastSection:
// Note insertBefore is called on the parent element, thus
// the lastSection.parentElement.
lastSection.parentElement.replaceChild(lastSection, sectionBeforeLastSection);
// Add sectionBeforeLastSection back at the end:
// Note we have a wrapping div aroudn the .section divs. Otherwise,
// appendChild will append the element after the button, as the
// parent would be the body.
lastSection.parentElement.appendChild(sectionBeforeLastSection);
};
.section {
border: 3px solid black;
height: 30px;
margin: 0 0 10px;
}
.a { background: red; }
.b { background: yellow; }
.c { background: cyan; }
#move {
border: 3px solid black;
background: none;
padding: 10px 15px;
font-family: monospace;
}
<div>
<div class="section a"></div>
<div class="section b "></div>
<div class="section c"></div>
</div>
<button id="move">MOVE LAST ONE UP</button>