【问题标题】:Access figcaption and img through figure id通过figure id访问figcaption和img
【发布时间】:2017-10-28 19:59:06
【问题描述】:

我真的很想一个人找出这个问题……抱歉问这个问题。我刚开始接触 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 属性。

【问题讨论】:

    标签: javascript html css figure


    【解决方案1】:

    您可以使用查询选择器:

    document.querySelector('#hg img');
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        您可以查看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 获取名称

        【讨论】:

          猜你喜欢
          • 2017-12-15
          • 1970-01-01
          • 2014-08-08
          • 1970-01-01
          • 1970-01-01
          • 2022-11-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多