我正在尝试使用一个普通的JavaScript选择器(不使用jQuery)来获得如下所示的相同选择:
$('[data-automationid=pictureupload_1]').parent().nextAll('input[type=text]')有人能帮帮我吗?我一直在挣扎。
发布于 2020-09-03 00:58:45
据我所知,DOM中没有nextAll方法,因此在不使用jQuery的情况下这样做有点棘手。
我们可以像这样使用生成器来迭代和过滤nextElementSibling:
function* myNextAll(e, selector) {
while (e = e.nextElementSibling) {
if ( e.matches(selector) ) {
yield e;
}
}
}
let e1 = document.querySelector("[data-automationid=pictureupload_1]").parentElement;
let siblings = [...myNextAll(e1, "input[type=text]")];发布于 2020-09-03 00:55:00
document.querySelector('[data-automationid=pictureupload_1]')选择起始节点.parentElement.children获取来自父节点(包括父节点本身)的所有兄弟姐妹。为了进行演示,迭代结果并通过test类更改背景。
如果你想试试:https://jsfiddle.net/7p8wt4km/2/
let result = [];
let par = document.querySelector('[data-automationid=pictureupload_1]').parentElement;
let sibling = par.parentElement.children;
let found = false;
for (let i=0; i< sibling.length; i++) {
if (!found && sibling[i] ===par) {
found = true;
continue;
} else if (found) {
let sib = sibling[i];
if (sib.nodeName !== 'INPUT' || sib.nodeType!= 1) continue;
result.push(sib);
}
}
result.forEach(el => { el.classList.add('test');});.test { background: green; }<div>
<div>
Sibling 0
</div>
<div>
Parent
<div data-automationid='pictureupload_1'>
pictureupload_1
</div>
</div>
<input type='text'>
<div type='text'>
Sibling 2
</div>
<input type='test'>
<input type='checkbox'>
</div>
发布于 2021-02-18 04:41:11
您可以尝试使用index元素获取我的代码。
const getIndex = (node, groupNode) => {
return [...groupNode].indexOf(node);
}
Element.prototype.nextAll = function(){
var allChildren = this.parentNode.children;
var index = getIndex(this, allChildren);
allChildren = [...allChildren].filter((item) => {
return getIndex(item, allChildren) > index;
});
return allChildren;
}https://stackoverflow.com/questions/63715008
复制相似问题