如何使用元素标记名称来爬上DOM树?

时间:2017-02-28 23:34:31

标签: javascript

我知道如何使用parentNode,children和id来爬上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();
});
&#13;
<div id='ex-container'>
<!--  everything goes here -->
</div>
&#13;
&#13;
&#13;

额外奖励:如何通过标签名称定位更近的兄弟姐妹?

2 个答案:

答案 0 :(得分:1)

结帐document.querySelector()。您可以在节点上使用<!--\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ Work section //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// --> <section id="work" class="paddingstandard"> <div class="container"> <h2 class="appear" data-animation="translatefrombottom">WORK</h2> <!-- Description --> <p class="aligncenter appear">Pellentesque erat velit, pretium vitae dui tempor, scelerisque posuere mi. Etiam fringilla scelerisque nulla volutpat vehicula. Donec tempus ut diam ac pharetra. Quisque quis odio convallis, imperdiet purus dignissim, tempor urna. Curabitur ut nisl nec orci scelerisque vehicula vitae eu nunc.</p> <!-- Isotope Filter --> <nav id="portfolionav" class="isotopeFilter aligncenter appear"> <a href="#" data-filter-value="*" class="is-checked">ALL</a> <a href="#" data-filter-value=".graphic" >GRAPHIC</a> <a href="#" data-filter-value=".slider">IMAGE SLIDERS</a> <a href="#" data-filter-value=".video">VIDEO</a> </nav> </div> <div id="portfoliogrid"> <!-- Begin item --> <div class="item width2 graphic"> <div class="rollover"> <div class="centerContainer hidden-xs"> <div> <a class="title" href="work-detail-1.html">CREATIVITY SPLASH</a> <a href="work-detail-1.html">VIEW DETAILS</a> </div> </div> </div> <!-- Item Image --> <img src="img/work/work-double-1.jpg" alt="Portfolio" /> </div> <!-- End item --> <div class="item manager" > <div class="rollover"> <div class="centerContainer hidden-xs"> <div> <a class="title" href="work-detail-2.html">IRRIGATE YOUR MIND</a> <a href="work-detail-2.html">VIEW DETAILS</a> </div> </div> </div> <img src="img/work/work-single-1.jpg" alt="Portfolio" /> </div> <div class="item graphic" data-url="article.html"> <div class="rollover"> <div class="centerContainer hidden-xs"> <div> <a class="title" href="work-detail-3.html">DOMOTIC</a> <a href="work-detail-3.html">VIEW DETAILS</a> </div> </div> </div> <img src="img/work/work-single-2.jpg" alt="Portfolio" /> </div> <div class="item developer" > <div class="rollover"> <div class="centerContainer hidden-xs"> <div> <a class="title" href="work-detail-4.html">JOURNEY TO THE LAND OF TEA</a> <a href="work-detail-4.html">VIEW DETAILS</a> </div> </div> </div> <img src="img/work/work-single-3.jpg" alt="Portfolio" /> </div> <div class="item graphic" > <div class="rollover"> <div class="centerContainer hidden-xs"> <div> <a class="title" href="work-detail-5.html">FUTURE OF COMMERCE</a> <a href="work-detail-5.html">VIEW DETAILS</a> </div> </div> </div> <img src="img/work/work-single-4.jpg" alt="Portfolio" /> </div> <div class="item manager" > <div class="rollover"> <div class="centerContainer hidden-xs"> <div> <a class="title" href="work-detail-6.html">CORPORATE DESIGN</a> <a href="work-detail-6.html">VIEW DETAILS</a> </div> </div> </div> <img src="img/work/work-single-5.jpg" alt="Portfolio" /> </div> <div class="item graphic" > <div class="rollover"> <div class="centerContainer hidden-xs"> <div> <a class="title" href="work-detail-7.html">PHOTO STUDIO</a> <a href="work-detail-7.html">VIEW DETAILS</a> </div> </div> </div> <img src="img/work/work-single-6.jpg" alt="Portfolio" /> </div> <div class="item width2 slider" > <div class="rollover"> <div class="centerContainer hidden-xs"> <div> <a class="title" href="work-detail-8.html">LOOKING FOR AWESOME IDEAS</a> <a href="work-detail-8.html">VIEW DETAILS</a> </div> </div> </div> <img src="img/work/work-double-2.jpg" alt="Portfolio" /> </div> <div class="item developer" > <div class="rollover"> <div class="centerContainer hidden-xs"> <div> <a class="title" href="work-detail-9.html">APP MARKET</a> <a href="work-detail-9.html">VIEW DETAILS</a> </div> </div> </div> <img src="img/work/work-single-7.jpg" alt="Portfolio" /> </div> <div class="item developer" > <div class="rollover"> <div class="centerContainer hidden-xs"> <div> <a class="title" href="work-detail-10.html">DATA STORAGE</a> <a href="work-detail-10.html">VIEW DETAILS</a> </div> </div> </div> <img src="img/work/work-single-8.jpg" alt="Portfolio" /> </div> <div class="item width2 video"> <div class="rollover"> <div class="centerContainer hidden-xs"> <div> <a class="title" href="work-detail-11.html">VIDEO TIMELAPSE</a> <a href="work-detail-11.html">VIEW DETAILS</a> </div> </div> </div> <img src="img/work/work-double-3.jpg" alt="Portfolio" /> </div> <div class="item developer" > <div class="rollover"> <div class="centerContainer hidden-xs"> <div> <a class="title" href="work-detail-12.html">CLEAN DESIGN</a> <a href="work-detail-12.html">VIEW DETAILS</a> </div> </div> </div> <img src="img/work/work-single-9.jpg" alt="Portfolio" /> </div> </div><!-- end "portfoliogrid"--> </section>来按选择器选择子节点。实施例

querySelector()

const parent = document.getElementById('someID') const firstP = parent.querySelector('p:first-child') 会引用ID为parent的元素,然后我们可以使用someID上的querySelector来选择第一个parent标记。

这是一个有效的例子:

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

firstP.style.color = 'red'
&#13;
&#13;
&#13;

您可以使用相关的document.querySelectorAll()创建匹配元素数组,并按照您想要的方式执行某些操作,如下所示:

&#13;
&#13;
<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>
&#13;
const parent = document.getElementById('someID')
const pees = parent.querySelectorAll('p')

parent.pees = Array.from(pees)

parent.pees[0].style.color = 'red'
&#13;
&#13;
&#13;

答案 1 :(得分:1)

添加了一些属性来解决源代码中评论的问题(无法理解问题)。详情请参阅代码段中的/* */

<强>段

//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>