如何在元素后追加元素、替换网站按钮及选中前置元素?
问题解决与实操方案
1. 追加元素嵌套的原因与正确实现
你用element.append()会把新元素作为子元素插入目标元素内部,这就是新按钮被包在原按钮里的原因。要在目标元素的同级后方追加元素,用以下两种方法:
原生JS实现
方法一:insertAdjacentElement(兼容性好)
const targetBtn = document.getElementById('itemCaptureResultRightButton'); const newBtn = document.createElement('button'); newBtn.id = 'itemCaptureResultRightButtonSW'; newBtn.innerHTML = '>'; newBtn.className = 'btn'; // 直接赋值避免多余空格问题 targetBtn.insertAdjacentElement('afterend', newBtn);
方法二:after()(现代浏览器支持)
targetBtn.after(newBtn);
jQuery实现(若使用jQuery)
$('#itemCaptureResultRightButton').after(newBtn);
2. 选中目标元素的前置元素
前置元素指目标元素的同级前序元素,按需求选择:
- 直接取目标按钮的前一个同级元素(原生JS):
const prevSibling = targetBtn.previousElementSibling; - 取目标按钮所在
.col的前一个.col(原生JS):const prevCol = targetBtn.parentElement.previousElementSibling; - jQuery写法:
// 取按钮的前一个同级元素 $('#itemCaptureResultRightButton').prev(); // 取按钮所在.col的前一个.col $('#itemCaptureResultRightButton').parent().prev('.col');
3. 替代$('.col')[2]的更优选择器
索引选择器依赖DOM结构顺序,易失效,推荐通过按钮ID定位父容器:
原生JS
// 定位右按钮所在的.col const targetCol = document.getElementById('itemCaptureResultRightButton').parentElement; // 定位左按钮所在的.col const leftCol = document.getElementById('itemCaptureResultLeftButton').parentElement;
jQuery
// 定位右按钮所在的.col const targetCol = $('#itemCaptureResultRightButton').closest('.col'); // 定位左按钮所在的.col const leftCol = $('#itemCaptureResultLeftButton').closest('.col');
内容的提问来源于stack exchange,提问作者hafen19
相关产品推荐
相关产品推荐

