1

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.

Zombo
  • 1
  • 62
  • 391
  • 407
Conor
  • 721
  • 1
  • 6
  • 18
  • 2
    possible duplicate of [best way to get child nodes](http://stackoverflow.com/questions/10381296/best-way-to-get-child-nodes) – Ainar-G Aug 18 '15 at 14:00

3 Answers3

0

After retrieving the list element with document.getElementById('myList') and assigning it to list, you can retrieve its children with list.getElementById(n) where n is the id. (Or you could continue to use document.getElementById if the element IDs are unique in the document, as they are supposed to be.)

Demonstration:

function print(s) {
  document.write(s + '<br />');
}

var list = document.getElementById('myList');
for (var i = 1; i <= 3; ++i) {
  var child = list.getElementById(i);
  print(child.innerHTML);
}
<div id="myList">
  <div id="1"> one </div>
  <div id="2"> two </div>
  <div id="3"> three </div>
</div>
Michael Laszlo
  • 12,009
  • 2
  • 29
  • 47
  • A good approach but unfortunately I will not know the content of the list or size, which makes this solution limited. – Conor Aug 18 '15 at 14:20
0

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;
Pete
  • 57,112
  • 28
  • 117
  • 166
0

You can try it with document.querySelector, works fine with all browsers and ie 9

See a demo on jsfiddle

var listItems = document.querySelectorAll("#myList .list-item");
  for(var i=0; i < listItems.length; i++){
    console.info(listItems[i].id);
}
<div id="myList">
  <div class="list-item" id="1" >item 1</div>
  <div class="list-item" id="2" >item 2</div>
  <div class="list-item" id="3" >item 3</div>
</div>
deFreitas
  • 4,196
  • 2
  • 33
  • 43