HTML DOM Element firstChild 属性

ການອະທິບາຍ ແລະ ການນໍາໃຊ້

firstChild ທີ່ປະສົງຂອງຫົວຂໍ້ພັດທະນາການຄັ້ງທຳອິດຂອງຫົວຂໍ້ພັດທະນາການ ທີ່ Node object.

firstChild ທາງປະສົງຂອງ

firstChild ທາງປະສົງຂອງ childNodes[0] ຄືກັນ.

ຄວາມຕ້ອງເຫັນ:

firstChild ການກັບຄືນຫົວຂໍ້ພັດທະນາການຄັ້ງທຳອິດ:

ຈຸດຈັກລະຫວ່າງຫົວຂໍ້ກໍ່ແມ່ນຫົວຂໍ້ຂັດຄວາມ.

ການແທນທີ່:

firstElementChild 属性 - firstElementChild ທີ່ປະສົງຂອງຫົວຂໍ້ພັດທະນາການຄັ້ງທຳອິດ (ບໍ່ພິຈາລະນາຫົວຂໍ້ຂັດຄວາມ ແລະ ຊອງຂັດຄວາມ).

ບໍ່ອອກຈາກ:

ທີ່ປະສົງຂອງຫົວຂໍ້

ທີ່ປະສົງຂອງຫົວຂໍ້

ທີ່ປະສົງຂອງຫົວຂໍ້

ທີ່ປະສົງຂອງຫົວຂໍ້

ທາງປະສົງຫົວຂໍ້

ທີ່ປະສົງຂອງຫົວຂໍ້

ທີ່ປະສົງຂອງຫົວຂໍ້

ທີ່ປະສົງຂອງຫົວຂໍ້

ທີ່ປະສົງຂອງຫົວຂໍ້

ຄວາມລາຍງາຍ

ຕົວຢ່າງ 1

ການກັບຄືນ HTML ຂອງຫົວຂໍ້ພັດທະນາການ <ul>

document.getElementById("myList").firstChild.innerHTML;

Try it yourself

ຕົວຢ່າງ 2

ການເອົາຄວາມຂອງຫົວຂໍ້ພັດທະນາການ <select>

let text = document.getElementById("mySelect").firstChild.text;

Try it yourself

ຕົວຢ່າງ 3

ຄວາມສະຫຼົບຂອງຈຸດຈັກ.

ພະຍາຍາມການເອົາຊື່ຂອງຫົວຂໍ້ພັດທະນາການ "myDIV"

<div id="myDIV">
  <p>Looks like first child</p>
  <p>Looks like last Child</p>
</div>
<script>
let text = document.getElementById("myDIV").firstChild.nodeName;
</script>

Try it yourself

Example 4

But, if you remove spaces from the source, there is no #text node in "myDIV":

<div id="myDIV"><p>First child</p><p>Last Child</p></div>
<script>
let text = document.getElementById("myDIV").firstChild.nodeName;
</script>

Try it yourself

HTML nodes and elements

In HTML DOM(Document Object Model)In HTML documents, HTML documents are a set of nodes that have(or do not have)child nodes.

NodeIs an element node, text node, and comment node.

ElementSpaces between them are also text nodes.

Element is just an element node.

Child nodes and child elements

childNodes ReturnsChild nodes(Element nodes, text nodes, and comment nodes).

children ReturnsChild elements(Not text and comment nodes).

firstChild and firstElementChild

firstChild Returns the firstChild nodes(Element node, text node, or comment node). Spaces between elements are also text nodes.

firstElementChild Returns the firstChild elements(Does not return text nodes and comment nodes).

lastChild and lastElementChild

lastChild Returns the lastChild nodes(Element node, text node, or comment node). Spaces between elements are also text nodes.

lastElementChild Returns the lastChild elements(Does not return text nodes and comment nodes).

Syntax

element.firstChild

or

node.firstChild

Return Value

Type Description
Node

The first child of the node.

If there is no child, it returns null.

Browser Support

element.firstChild It is a DOM Level 1 (1998) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support