2017-10-28 57 views
1

我真的很想單獨找到這個......抱歉提出這個問題。我剛開始學習HTML,CSS和JavaScript。通過圖號訪問figcaption和img

我只想通過圖的id來訪問我的圖的imgfigcaption

<div id="grid"> 
    <figure id="hg"> 
     <img src="sml1.png"/> 
     <figcaption>0</figcaption> 
    </figure> 
</div> 

document.getElementById("hg").children嘗試過,但似乎並沒有爲我工作。也許我用它錯了?

我甚至想做甚麼?我真的不想給img和figcaption元素一個id屬性。

回答

1

可以使用queryselector:

document.querySelector('#hg img'); 
1

儘量document.getElementById("hg").firstElementChilddocument.getElementById("hg").children[0]

Node.children返回現場的HTMLCollection,不是一個單一的元素。 MDN

0

你可以看看Node.childNodes來檢查你的元素是否有孩子。

Node.childNodes只讀屬性返回第一個子節點被分配索引0

var myfigure = document.getElementById('hg'); 
 
// does you ID exists ? 
 
if (myfigure.hasChildNodes()) // has it got any child ? 
 
{ 
 
    var children = myfigure.childNodes; 
 
    // if it does, get them 
 
    for (var i = 0; i < children.length; i++) { 
 
    // go through all children 
 
    if (children[i].nodeName == 'IMG') { 
 
     // is it an img tag 
 
     children[i].style.border = "solid"; // apply some style or whatever else 
 
    } 
 
    // another test 
 
    if (children[i].nodeName == 'FIGCAPTION') { 
 
     children[i].style.color = "red"; 
 
    } 
 
    } 
 
}
<div id="grid"> 
 
    <figure id="hg"> 
 
    <img src="http://dummyimage.com/200&text=sml1.png" /> 
 
    <figcaption>caption</figcaption> 
 
    </figure> 
 
</div>

給定元素的子節點的實時採集節點集合中的項目是對象而不是字符串。要從節點對象獲取數據,請使用其屬性(例如elementNodeReference.childNodes[1].nodeName以獲取名稱