Sommario
Restituisce l'oggetto Node che è primo figlio del nodo dato, oppure null se il nodo non ha figli.
Sintassi
PrimoNodoFiglio =node.firstChild;
PrimoNodoFiglio è un riferimento al primo nodo figlio di node, oopure è null se node non ha figli.
Esempio
Questo esempio mostra l'uso di firstChild e come un nodo di testo(uno spazio bianco) può portare a errori nell'uso di questa proprietà.
<p id="para-01">
<span>First span</span>
</p>
<script type="text/javascript">
var p01 = document.getElementById('para-01');
alert(p01.firstChild.nodeName)
</script>
In questo esempio, l'alert mostrerà '#text' perchè un nodo testuale è presente fra il tag di chiusura di P e il tag di apertura di SPAN.
Un'altro nodo testuale è presente fra il tag di chiusura di SPAN e quello di P. In totale i nodi figli di P sono tre, ma solo il secondo(cioè l'elemento SPAN) è in genere utile allo script.
Eliminando gli spazi fra i tag il firstChild di P è SPAN:
<p id="para-01"><span>First span</span></p>
<script type="text/javascript">
var p01 = document.getElementById('para-01');
alert(p01.firstChild.nodeName)
</script>
e ora l'alert mostrerà 'SPAN'.
Note
Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup.
Therefore a node obtained, for example, using Node.firstChild or Node.previousSibling may refer to a
whitespace text node rather than the actual element the author intended to get.
See Whitespace in the DOM and W3C DOM 3 FAQ: Why are some Text nodes empty? for more information.