2013-10-21 107 views
0

HTML代碼的子節點:的Javascript得到一個div

<div id="section"> 
    <div id="title" onclick="hideBody()"></div> 
    <div id="body"></div> 
</div> 

我如何可以訪問使用this.id="body"元素...?
實例:
this.parent.child[1];

+0

[獲取該燒製使用jQuery一個事​​件的元素的ID]的可能重複(HTTP:/ /stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event-using-jquery) – isherwood

+0

什麼是「this」?提供更多信息。 –

+0

@AlfredoOsorio看看例子 – Xriuk

回答

1

您可以使用nextElementSibling

實施例:

function hideBody(el) { 
    'use strict'; 
    var sibling = el.nextElementSibling; 
    console.log(sibling); 

    sibling.style.visibility = 'hidden'; 
} 

參見jsFiddle

至於回答關於子節點的原始問題,有一個childNodes屬性。例如:

var children = document.getElementById('section').childNodes; 

相對於 「this」(在hideBody函數示出):

function hideBody(el) { 
    'use strict'; 
    var children = el.parentNode.childNodes; 
    console.log(children); 

    children[1].style.visibility = 'hidden'; 
} 
0

我不知道用 '這個' 爲宜這裏,但你當然可以傳遞事件,抓住點擊目標的ID:

http://jsfiddle.net/isherwood/6k7fc/

<div id="title" onclick="hideBody(event)"></div> 

function hideBody(event) { 
    var myId = event.target.id; 
    var myEl = document.getElementById(myId); 
    ... do stuff with myEl ... 
} 
+0

我有多個相同的ID – Xriuk

+0

然後你的HTML是無效的,你應該先修復。 - ) – isherwood