0

我目前正在尝试选择childNode一个元素。这就是我试图这样做的方式:

var postBody_elem = elem.parentNode.parentNode.childNodes['post'].childNodes['postBody'];

我也试过:

elem.parentNode.parentNode.childNodes[0].childNodes[1];

我知道这是我测试过的问题childNodes,而不是问题。parentNodes

这是我正在做的简化结构:

<section id = 'postWrapper'>                          //This is the Second Parent.
  <article id = 'post'>                               //This should be the First Child.
    <section id = 'postInfo'>
      <section id = 'postTitle'></section>
      <section id = 'poster'></section>
      <section id = 'postDate'></section>
    </section>
    <section id = 'postBody'>                       //This should be the Second Child.
    </section>
  </article>
  <section id = 'postBar'>                          //This is the First Parent.
    <img id = 'portrait'>
    <section id = 'editButton'>Edit</section>       //This is the var elem.
    <section id = 'deleteButton'>Delete</section>
  </section>
</section>

我必须'postBody'通过浏览父节点和子节点来引用 的原因是因为这种格式被迭代了很多次。

--这让我想到了我的问题,上面的代码行在谷歌浏览器中有效,但在 FireFox 中无效,我尝试了很多变体,但控制台给了我未定义的错误。我已经检查过元素是否正确声明,这只是我认为浏览器处理它的方式之间的区别。

如果有人有答案,我希望它是关于如何引用我展示的元素,而不是关于我如何不正确地用于id多个元素的讲座,因为在这种情况下这不是问题(据我所知,因为它适用于 Chrome)。

谢谢。

4

2 回答 2

1

第一种方法在 Firefox 中不起作用,因为它似乎是非标准的,第二种方法不起作用,因为您没有意识到 childNodes 也包含文本节点。要获得您想要的元素,请尝试

elem.parentNode.parentNode.childNodes['1'].childNodes['3']

http://jsfiddle.net/mowglisanu/UqZVn/

于 2012-12-05T04:48:48.680 回答
1

后代的一些替代方案(这些在 Firefox 中工作,我不知道其他浏览器的支持):

  1. elem.children不包括文本节点,所以elem.parentNode.parentNode.children[0].children[1]会起作用

  2. 您可以使用elem.parentNode.parentNode.getElementsByTagName('section')[4](0=postInfo, 1=postTitle, 2=poster, 3=postDate)

  3. elem.parentNode.parentNode.querySelector('article > section + section')例如,您可以使用

  4. 我认为elem.parentNode.previousElementSibling.lastElementChild也有效

于 2012-12-05T11:45:36.500 回答