3

I am writing code and I came up to issue where I need to select something other than firstChild, but I don't know the syntax to write this code. I scoured online hoping to find some API documentation on them but have found nothing. What is the code to select other child elements? Like say I wanted to select the 4th child in a element, what is the code for that? I only know the code to select the 1st child element.

dom.el("playeravatar").firstChild.innerHTML = '<img src="dwarfs/dwarf14.jpg" style="max-width: 200px; max-height: auto" alt="Dwarf">';
Charlie74
  • 2,883
  • 15
  • 23
Shawn
  • 1,175
  • 2
  • 11
  • 20

2 Answers2

2

You can use DOM object children which provide you all children of an element.

For example if you want get the property text of the third children (0,1, 2) of an element called playeravatar, you code should be:

var c = document.getElementById("playeravatar").children[2].text;
caballerog
  • 2,679
  • 1
  • 19
  • 32
0

You can use jQuery selector :nth-child(n) for example if you need to select the 4th child in a element use :nth-child(4)

<div id="parent">
  <div>
    <span>first-child</span>
  </div>
  <div>
    <span>second-child</span>
  </div>
  <div>
    <span>third-child</span>
  </div>
  <div>
    <span>fourth-child</span>
  </div>
</div>

$(document).ready(function () {
      alert($("#parent div:nth-child(4)").html());
      $("#parent div:nth-child(4)").html('<a href="http://www.google.com">Google</a>');
});