2011-10-17 34 views
3
的innerHTML的

我有以下的HTML:設置nextSibling

<h3 onclick="replaceNextChild(this);">Some content...</h3> 
<div>Div that I am interested in replacing</div> 

我有以下的JavaScript:

<script> 
function replaceNextChild(element) { 

    element.nextSibling.innerHTML = "I replaced the next element in the DOM"; 
} 
</script> 

爲什麼是它的JavaScript不能取代的下一個元素?我也使用jQuery,並不介意jQuery解決方案。

+1

如果您有jQuery的加載,你還不如把它作爲[@亞歷克斯的答案](http://stackoverflow.com/questions/7788529/set-innerhtml-of-nextsibling/證明7788537#7788537)。這首先是它的要點。 ;) – user113716

回答

8

因爲在很多瀏覽器中,nextSibling將是一個空文本節點。

改爲使用nextElementSibling

element.nextElementSibling.innerHTML = "I replaced the next element in the DOM"; 

您需要爲不支持它的瀏覽器創建一個函數。

(element.nextElementSibling || nextElementSibling(element)) 
          .innerHTML = "I replaced the next element in the DOM"; 

function nextElementSibling(el) { 
    if(el) { 
     while((el = el.nextSibling) && el.nextSibling.nodeType !== 1); 
     return el; 
    } 
} 
+1

+1 beautiful,Patrick! – alex

+0

感謝@alex。希望我的功能正確。 – user113716

+0

更正了代碼示例,它不正確,而是查看nextnode的類型,之後查看節點的類型(el.nodeType而不是el.nextSibling.nodeType,el已經是該點的下一個節點) – redorkulated

4

我使用jQuery所以使用該庫方法的任何解決方案,將有助於太

好了,改變它只是一點點:P

$(this).next().html('I replaced the next element in the DOM'); 

因爲它是一個文本節點。設置nodeValuedata相反,如果你想改變文本節點,否則可能改變你的函數...

function replaceNextChild(element) { 

    do { 
     element = element.nextSibling; 
    } while (element.nodeType != 1); 

    element.innerHTML = "I replaced the next element in the DOM"; 
} 

jsFiddle

但實際上Patrick's answer(使用nextElementSibling要好得多)。

+0

+1爲下一個節點選項。 – user113716

+1

啊,現在使用jQuery。這肯定會改變事情。 :) – user113716

+0

+1很棒的jquery例子!我使用它:..... function replaceNextChild(element){$(element).next()。html('new content!');} –

0

nextSibling屬性在同一樹級別中返回緊接在指定節點後面的節點。

返回的節點作爲節點對象返回。

此屬性與nextElementSibling的區別在於nextSibling將下一個兄弟節點作爲元素節點,文本節點或註釋節點返回,而nextElementSibling將下一個兄弟節點作爲元素節點返回(忽略文本和註釋節點)。

此屬性是隻讀的。

http://www.w3schools.com/jsref/prop_node_nextsibling.asp