我知道如何使用parentNode,children和id来上下DOM,但我不知道如何通过标签名称来访问兄弟或子元素。如何使用元素标记名称上下DOM树?
这个代码示例有点人为的,但我希望你可以用它来帮助我使用这些元素标签名称进行导航的一般答案。
//fluff to create an example
const outArr = Array(10).fill(0).map((el, i) => { return (
'<p>Title ' + i + '</p>' +
'<p>Decription ' + i + '</p>' +
'<span>Other ' + i + '</span>' +
'<button>Click to Like' + i + '!</button>'
)});
const output = outArr.join(',');
document.getElementById('ex-container').innerHTML = output;
//targeting inside anon event function for simplicity
document.getElementById('ex-container').addEventListener('click', function(e) {
if (e.target.localName == 'button') {
const curEl = e.target
const parent = curEl.parentNode;
//I can access the parent node. If I had id's, I know I could targert
//children with those. How would I target the siblings, and from the
//parentNode target a specific child by element tagName, such as p?
console.log('curEl: ', curEl);
console.log('parent: ', parent);
}
e.stopPropagation();
});
<div id='ex-container'>
<!-- everything goes here -->
</div>
奖励:我如何透过标签名称较近p兄弟姐妹?
你想做的事可以用jQuery或类似的库轻松完成一切。要做到这一点,没有jQuery和直接的DOM功能,请查看https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName和Element上定义的其他函数。 –
“更近”是什么意思?因为在你显示的情况下,最接近''button'的'p'将会是下面带有“Title”的'p',除非它是最后一个'button',在这种情况下它将会不同。 –
@Daniel Williams我知道如何通过tagName来定位元素,我想知道如何在DOM上遍历它们。例如:e.target.parentNode.span(但这不起作用,我在寻找正确的语法)。 –