2012-12-05 29 views
0

我正在嘗試選擇元素的childNode。 這是我在嘗試這樣做:JS-從FireFox中選擇childNodes的問題

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中工作)。

謝謝。

+0

它重複了很多次。 ..你正在使用「獨特」ID? – Neil

+0

@尼爾是的,是的,我是。我知道爲什麼嗎?不,但我喜歡。 – MichaelMitchell

+0

對不起教你,我忽略了你最後一句話。 – Neil

回答

1

第一種方法在Firefox中不起作用,因爲它似乎不是標準的,第二種方法不起作用,因爲您沒有意識到childNodes也包含文本節點。爲了得到你想要嘗試

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

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

+0

你介意解釋爲什麼這是有效的嗎? – MichaelMitchell

+0

@MichaelMitchell標籤之間的空格是文本節點和計算元素的子節點。在你的標記中,

'的第一個子節點是文本節點(標記之間的空白),而'
'是第二個子節點,其他元素也是一樣的。 – Musa

+0

感謝您的解釋! – MichaelMitchell

1

留給後人一些替代的元素(在Firefox這些工作,我不知道在其他瀏覽器支持的副手):

  1. elem.children排除文本節點,所以elem.parentNode.parentNode.children[0].children[1]本來可以工作

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

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

  4. 我覺得elem.parentNode.previousElementSibling.lastElementChild也適用

+0

我喜歡排名第一,感謝<3。 我發現我使用迭代ID來查看哪些標記是在代碼中查找的,它們從來沒有實際使用過,大聲笑 – MichaelMitchell