2017-02-28 3 views
1

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個の兄弟をターゲットにすることができますか?

+1

あなたがしたいすべてが簡単にjqueryのまたは類似のライブラリーを用いて行うことができます。 jqueryとDOM関数を使わずにそれを行うには、https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagNameとElementに定義されている残りの関数を調べてください。 –

+0

「近い」とはどういう意味ですか?あなたが表示している場合、最後の 'button'でない限り、' button'に最も近い 'p'は' Title'を含む 'p'になります。 –

+0

@Daniel Williams tagNameで要素をターゲットする方法を知っていますが、DOMでそれらをトラバースする方法を知りたいと思います。例:e.target.parentNode.span(ただし、これは機能しません。適切な構文を探しています)。 –

答えて

1

ソースにコメントされた質問に対処するためのいくつかのプロパティを追加しました(質問を理解できませんでした)。詳細は、スニペットの/* */によるコメントです。

SNIPPET

//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) { 
 
    /* Compare the currentTarget to the target, this way it 
 
    || will give you target to whatever you clicked not just a 
 
    || button 
 
    */ 
 
    if (e.target !== e.currentTarget) { 
 
    const curEl = e.target 
 
    const parent = curEl.parentNode; 
 
    // How would I target the siblings, 
 
    var bigBro = curEl.previousElementSibling; 
 
    var lilBro = curEl.nextElementSibling; 
 
    /* Collect all children of parent */ 
 
    var kids = parent.children; 
 
    // from the parentNode target a specific child by element tagName, such as p? 
 
    /* Same results for both with one difference being the 
 
    || first one is "live" NodeList the other "static" 
 
    || NodeList. 90% of the time, it's safer to go "static" 
 
    || using querySelectorAll() 
 
    */ 
 
    var paragraphsByTag = parent.getElementsByTagName('p'); 
 
    var paragraphsBySel = parent.querySelectorAll('p'); 
 

 
    console.log('curEl: ', curEl); 
 
    console.log('parent: ', parent); 
 
    console.log('bigBro: ', bigBro); 
 
    console.log('lilBro: ', lilBro); 
 
    /* Add .length property to get total number */ 
 
    console.log('Total Kids: ', kids.length); 
 
    /* NodeLists are array-like but not true arrays, so use 
 
    || Array.from() to convert them into true arrays. 
 
    */ 
 
    console.log('Paragraphs are: ', Array.from(paragraphsBySel)); 
 
    } 
 
    /* Specific by tagName is almost an oxymoron. If you 
 
    || want to target a specific element but only have 
 
    || tagNames, then as you commented, by index is the way 
 
    || to go. 
 
    */ 
 
    console.log('The 6th paragraph is: ', Array.from(paragraphsBySel)[5]); 
 

 
    e.stopPropagation(); 
 
});
<div id='ex-container'> 
 
    <!-- everything goes here --> 
 
</div>

+0

私は、これが動きにかなり包括的で、例のコードを使って子供たちにアクセスするさまざまな方法をカバーしているので、これを使うつもりです。私はまだ、DOMの周りをより効率的にトラバースして歩く方法を見つけることを願っています。 console.log(e.target == e.target.parentNode.span.previousElementSibling.previousElementSiblingp.nextElementSiblingbutton)// true trueなどのログを返します。 –

+0

jQueryを使用すると、[chaining]という機能があります(http://www.jquery tutorial.net/introduction/method-chaining/)を参照してください。連鎖すると、メソッドを一緒にリンクすることができます。私は通常、初心者にはjQueryを提案しません。なぜなら、JavaScriptを適切に理解していないと思っているからですが、DOMをよく把握しているかのように見えます。 DOMをトラバースする最も完全なメソッドを探している場合、[treewalker](https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker)はオプションですが、構文と操作は次のとおりです少し異なる。 – zer00ne

1

チェックアウトdocument.querySelector()ノード上でquerySelector()を使用して、セレクタによって子ノードを選択することができます。 Ex。

const parent = document.getElementById('someID') 
const firstP = parent.querySelector('p:first-child') 

parentsomeIDのIDを持つ要素をrefのだろう、そこから我々は最初のpタグを選択するparentquerySelectorを使用することができます。

:あなたはこのように、一致する要素の配列を作成し、必要な線に沿って何かを行うには、関連 document.querySelectorAll()を使用することができます

const parent = document.getElementById('someID') 
 
const firstP = parent.querySelector('p:first-child') 
 

 
firstP.style.color = 'red'
<div id="someOtherID"> 
 
    <p>First</p> 
 
    <p>Second</p> 
 
    <p>Third</p> 
 
    <p>Fourth</p> 
 
</div> 
 
<div id="someID"> 
 
    <p>First</p> 
 
    <p>Second</p> 
 
    <p>Third</p> 
 
    <p>Fourth</p> 
 
</div>

:ここ

は、実施例です

const parent = document.getElementById('someID') 
 
const pees = parent.querySelectorAll('p') 
 

 
parent.pees = Array.from(pees) 
 

 
parent.pees[0].style.color = 'red'
<div id="someOtherID"> 
 
    <p>First</p> 
 
    <p>Second</p> 
 
    <p>Third</p> 
 
    <p>Fourth</p> 
 
</div> 
 
<div id="someID"> 
 
    <p>First</p> 
 
    <p>Second</p> 
 
    <p>Third</p> 
 
    <p>Fourth</p> 
 
</div>

+0

これは間違いなく助けになります!追加された一般的なメソッドを使用してこれを行う方法を知っていますか? e.target.parentNode.firstElement.pなどのようなもの? –

+0

私は別の例でこのソリューションを更新しました。 –

+0

これは私を勝利から一歩遠ざかるようにします。私はe.target.parentNode.querySelectorAll( 'p')[0]のようにquerySelectorを連鎖させることで疑似トラバースが可能になりました。私が望むのは、parentNodes、children、idのようにタグをたどる方法で焼き盛りがあるということです。 –

関連する問題