dongxiatuo9827 2015-08-18 13:39
浏览 12
已采纳

访问模板生成的子元素

In my application I'm generating HTML with a Go template. I pass a list to a template that resembles this:

<div id="myList">
 {{ Loop }}
   <div id="{{.loopIndex}}">
 {{ End loop }}
</div>

I now want to access the individual children in JavaScript according to ID. These are not 'elements', so I can't use the HTML DOM getAttribute() method, or access element.id.

I want to do something like this:

  var listElement = document.getElementById("myList");
  var listElements = listElement.childNodes;

  for (i=0; i < listElements.length; i++) {
     alert(listElements[i].id);
  }

How would I do this? Is there any way to convert the objects in my list to DOM Elements? The example I gave is a lot simpler than my actual code, but it would follow the same approach, I imagine.

  • 写回答

3条回答 默认 最新

  • dongwei1921 2015-08-18 14:08
    关注

    You could use getElementsByTagName:

    var listElement = document.getElementById("myList");
    var listElements = listElement.getElementsByTagName('div'); // could also use listElement.children;
    
    for (i = 0; i < listElements.length; i++) {
      alert(listElements[i].id);
    }
    <div id="myList">
      <div id="1"></div>
      <div id="2"></div>
      <div id="3"></div>
    </div>

    Or just children:

    var listElements = listElement.children;
    
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM