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'でない限り、' button'に最も近い 'p'は' Title'を含む 'p'になります。 –
@Daniel Williams tagNameで要素をターゲットする方法を知っていますが、DOMでそれらをトラバースする方法を知りたいと思います。例:e.target.parentNode.span(ただし、これは機能しません。適切な構文を探しています)。 –