通过figure id访问figcaption和img

Access figcaption and img through figure id

我真的很想一个人找出来...抱歉问这个问题。我刚开始接触 HTML、CSS 和 JavaScript。

我只想通过人物的id访问我人物的imgfigcaption

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

我用 document.getElementById("hg").children 试过了,但这似乎对我不起作用。可能是我用错了?

我想做的事有可能吗?我真的不想给 img 和 figcaption 元素一个 id 属性。

您可以使用查询选择器:

document.querySelector('#hg img');

尝试document.getElementById("hg").firstElementChilddocument.getElementById("hg").children[0]

Node.children returns 一个实时 HTMLCollection,而不是单个元素。 MDN

您可以查看 Node.childNodes 以检查您的元素是否有子元素。

The Node.childNodes read-only property returns a live collection of child nodes of the given element where the first child node is assigned index 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>

The items in the collection of nodes are objects and not strings. To get data from node objects, use their properties (e.g. elementNodeReference.childNodes[1].nodeName to get the name