Parentnode

Definition and Usage

The childNodes property returns a collection of a node’s child nodes, as a NodeList object.


The nodes in the collection are sorted as they appear in the source code and can be accessed by index numbers. The index starts at 0.

Note: Whitespace inside elements is considered as text, and text is considered as nodes. Comments are also considered as nodes.

Tip: You can use the length property of the NodeList object to determine the number of child nodes, then you can loop through all child nodes and extract the info you want.

This property is read-only.

Tip: To return a collection of a node’s element nodes (excluding text and comment nodes), use the children property.

Tip: element.childNodes will produce the same result as the firstChild property.

Node Types

Documents, elements, attributes, and other aspects of an HTML or XML document has different node types.

There are 12 different node types, which may have children of various node types:

Node type Description Children
1 Element Represents an element Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
2 Attr Represents an attribute Text, EntityReference
3 Text Represents textual content in an element or attribute None
4 CDATASection Represents a CDATA section in a document (text that will NOT be parsed by a parser) None
5 EntityReference Represents an entity reference Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
6 Entity Represents an entity Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
7 ProcessingInstruction Represents a processing instruction None
8 Comment Represents a comment None
9 Document Represents the entire document (the root-node of the DOM tree) Element, ProcessingInstruction, Comment, DocumentType
10 DocumentType Provides an interface to the entities defined for the document None
11 DocumentFragment Represents a «lightweight» Document object, which can hold a portion of a document Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
12 Notation Represents a notation declared in the DTD None

Вставка узлов в DOM

Чтобы увидеть созданные нами текстовые узлы и элементы на интерфейсе, нужно вставить их в . Методы и используются для добавления элементов в начало, середину или конец родительского элемента, а используется для замены старого узла на новый.

Продемонстрируем это, добавив список к нашему HTML:

<ul>  <li>Get pizza</li>  <li>Get burgers</li>  <li>Get Doritos</li></ul>

Вот наша страница:

Скажем, мы хотим добавить новый пункт в конец списка. Сперва нам нужно создать элемент и добавить к нему текст, как мы делали раньше:

// Получить элемент ulconst list = document.querySelector('ul');// Создать новый элемент спискаconst newItem = document.createElement('li');newItem.textContent = 'Get nice cheese';

Теперь у нас есть элемент для нового списка! Добавляем его в конец списка, используя :

// Добавить элемент в конец спискаlist.appendChild(newItem);

И новый элемент добавлен в конец :

Чтобы добавить пункт в начало списка, создадим другой элемент (мы должны создать новый элемент, потому что нельзя использовать повторно):

// Создать новый элемент спискаconst anotherNewItem = document.createElement('li');anotherNewItem.textContent = 'Get Party Whistles';

Используем метод , чтобы добавить элемент в начало списка. В нем будет два аргумента: первый будет новым добавленным дочерним узлом, а второй — соседним узлом, следующим сразу за дочерним.

parentNode.insertBefore(newNode, nextSibling);

Так мы добавим новый элемент в начало списка:

// Добавить новый элемент в начало спискаlist.insertBefore(anotherNewItem, list.firstElementChild);


Теперь новый узел добавлен в начало списка!

Давайте теперь посмотрим, как можно заменить существующий узел новым, используя . Во-первых, создаем новый элемент:

const modifiedItem = document.createElement('li');modifiedItem.textContent = "Get Poppin' Jalapeno Doritos";

Метод также содержит два аргумента: новый узел и узел, который нужно заменить:

parentNode.replaceChild(newNode, oldNode);

В нашем примере заменяем третий дочерний элемент списка:

// Заменить элемент спискаlist.replaceChild(modifiedItem, list.children)

Используя комбинацию методов , и узлы и элементы можно вставлять в DOM где угодно!

Types

Biological

An individual’s biological parents are the persons from whom the individual inherits his or her genes. The term is generally only used if there is a need to distinguish an individual’s parents from their biological parents, For example, an individual whose father has remarried may call the father’s new wife their stepmother and continue to refer to their mother normally, though someone who has had little or no contact with their biological mother may address their foster parent as their mother, and their biological mother as such, or perhaps by her first name.,[citation needed]

Mother

A mother is a female who has a maternal connection with another individual, whether arising from conception, by giving birth to, or raising the individual in the role of a parent. More than one female may have such connections with an individual. Because of the complexity and differences of a mother’s social, cultural, and religious definitions and roles, it is challenging to define a mother to suit a universally accepted definition. The utilization of a surrogate mother may result in explication of there being two biological mothers.

Father

A father is a male parent of any type of offspring. It may be the person who shares in the raising of a child or who has provided the biological material, the sperm, which results in the birth of the child.

Grandparent

Grandparents are the parents of a person’s own parent, whether that be a father or a mother. Every sexually reproducing creature who is not a genetic chimera has a maximum of four genetic grandparents, eight genetic great-grandparents, sixteen genetic great-great-grandparents and so on. Rarely, such as in the case of sibling or half-sibling incest, these numbers are lower.

Методы

Наследует методы от своих родителей .

Вставляет как последний дочерний узел данного элемента.
Клонирует , и опционально, все его компоненты. По умолчанию, оно клонирует содержимое узла.
Вставляет первым данный в качестве параметра, непосредственно перед вторым, потомком данного элемента .
Возвращает флаг содержащий результаты теста, реализует ли реализация DOM конкретную особенность и поддерживается ли эта особенность конкретным узлом.
Очищает все текстовые узлы под этим элементом (поглотить смежный, удалить пустой).
Удаляет дочерний узел из текущего элемента, который должен быть потомком текущего узла.
Заменяет одного потомка из существующего на второй указанный в параметре.

More Examples

Example

Find out how many children a <div> element has:

var c = document.getElementById(«myDIV»).children.length;

Example

Change the background color of the second child element of a <div> element:

var c = document.getElementById(«myDIV»).children;c.style.backgroundColor = «yellow»;

Example

Get the text of the third child element (index 2) of a <select> element:

var c = document.getElementById(«mySelect»).children.text;

Example

Loop through all children of <body> and change their background color to red:


var c = document.body.children;var i;for (i = 0; i < c.length; i++) {  c.style.backgroundColor = «red»;}

References

  1. Nadine Taub; Beth Anne Wolfson; Carla M. Palumbo. The Law of Sex Discrimination. p. 374.
  2. Browne C. Lewis (2012). Papa’s Baby: Paternity and Artificial Insemination. p. 136.
  3. Louise I. Gerdes (2009). Reproductive Technologies. p. 25.
  4. Marian S Harris (2014). Racial Disproportionality in Child Welfare. p. 2.
  5. Bernard Roberts (2005). Evidence in the Psychological Therapies: A Critical Guidance for Practitioners. p. 149.
  6. Bromham, David (1990). Philosophical Ethics in Reproductive Medicine. p. 57.
  7. ^
  8. Francis, Darryl. «Iatrologs and Iatronyms.» Word Ways 4.2 (1971): 8.
  9. Davies, Jon. «Imagining intergenerationality: Representation and rhetoric in the pedophile movie.» GLQ: A Journal of Lesbian and Gay Studies 13.2 (2007): 369-385.

More Examples

Example

In this example, we demonstrate how whitespace may interfere with this property.

Get the node name of the first child node of a <div> element:

<!— Whitespace inside elements is considered as text, and text is considered as nodesIn this example, there is whitespace before <p>, before <span> and after <span>Therefore, the first child node of <div> is a #text node, and not the <p> element you expected —><div id=»myDIV»>  <p>Looks like first child</p>  <span>Looks like last Child</span></div> <script>var x = document.getElementById(«myDIV»).firstChild.nodeName;document.getElementById(«demo»).innerHTML = x; </script>

Example

However, if we remove the whitespace from the source, there are no #text nodes in <div>, which will make the <p> element the first child node:

<div id=»myDIV»><p>First child</p><span>Last Child</span></div> <script>var x = document.getElementById(«myDIV»).firstChild.nodeName;document.getElementById(«demo»).innerHTML = x;</script>

Example

Get the text of the first child node of a <select> element:

var x = document.getElementById(«mySelect»).firstChild.text;

More Examples

Example

Find out if a list has any child nodes. If so, remove its first child node (index 0):

// Get the <ul> element with id=»myList»var list = document.getElementById(«myList»);// If the <ul> element has any child nodes, remove its first child nodeif (list.hasChildNodes()) {  list.removeChild(list.childNodes);}

Before removing:

  • Coffee
  • Tea
  • Milk

After removing:

  • Tea
  • Milk

Example

Remove all child nodes of a list:

// Get the <ul> element with id=»myList»var list = document.getElementById(«myList»);// As long as <ul> has a child node, remove itwhile (list.hasChildNodes()) {     list.removeChild(list.firstChild);}

Before removing:

  • Coffee
  • Tea
  • Milk

After removing:

Example

Remove a <li> element with id=»myLI» from its parent element (without specifying its parent node):

var item = document.getElementById(«myLI»);item.parentNode.removeChild(item);

Before removing:

  • Coffee
  • Tea
  • Milk

After removing:

  • Coffee
  • Milk

Example

Remove a <li> element from its parent, and insert it again:

var item = document.getElementById(«myLI»);function removeLi() {   item.parentNode.removeChild(item);}function appendLi() {  var list = document.getElementById(«myList»);   list.appendChild(item);}

Example

Remove a <span> element from its parent and insert it to an <h1> element in another document:

var child = document.getElementById(«mySpan»);function removeLi() {  child.parentNode.removeChild(child);}function myFunction() {  var frame = document.getElementsByTagName(«IFRAME»)   var h = frame.contentWindow.document.getElementsByTagName(«H1»);   var x = document.adoptNode(child);  h.appendChild(x); }

Genetics

Parent–offspring conflict

An offspring who hates their father is called a misopater, one that hates their mother is a misomater, while a parent that hates their offspring is a misopedist. Parent–offspring conflict describes the evolutionary conflict arising from differences in optimal fitness of parents and their offspring. While parents tend to maximize the number of offspring, the offspring can increase their fitness by getting a greater share of parental investment often by competing with their siblings. The theory was proposed by Robert Trivers in 1974 and extends the more general selfish gene theory and has been used to explain many observed biological phenomena. For example, in some bird species, although parents often lay two eggs and attempt to raise two or more young, the strongest fledgling takes a greater share of the food brought by parents and will often kill the weaker sibling, an act known as siblicide.

Empathy

David Haig has argued that human fetal genes would be selected to draw more resources from the mother than it would be optimal for the mother to give, a hypothesis that has received empirical support. The placenta, for example, secretes allocrine hormones that decrease the sensitivity of the mother to insulin and thus make a larger supply of blood sugar available to the fetus. The mother responds by increasing the level of insulin in her bloodstream, the placenta has insulin receptors that stimulate the production of insulin-degrading enzymes which counteract this effect.

Definition and Usage

The firstElementChild property returns the first child element of the specified element.

The difference between this property and firstChild, is that firstChild returns the first child node as an element node, a text node or a comment node (depending on which one’s first), while firstElementChild returns the first child node as an element node (ignores text and comment nodes).

This property is read-only.

Tip: Use the children property to return any child element of a specified element. children will produce the same result as firstElementChild.

Tip: To return the last child element of a specified element, use the lastElementChild property.

JavaScript

JS Array concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() forEach() from() includes() indexOf() isArray() join() keys() length lastIndexOf() map() pop() prototype push() reduce() reduceRight() reverse() shift() slice() some() sort() splice() toString() unshift() valueOf()

JS Boolean constructor prototype toString() valueOf()

JS Classes constructor() extends static super

JS Date constructor getDate() getDay() getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCFullYear() getUTCHours() getUTCMilliseconds() getUTCMinutes() getUTCMonth() getUTCSeconds() now() parse() prototype setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime() setUTCDate() setUTCFullYear() setUTCHours() setUTCMilliseconds() setUTCMinutes() setUTCMonth() setUTCSeconds() toDateString() toISOString() toJSON() toLocaleDateString() toLocaleTimeString() toLocaleString() toString() toTimeString() toUTCString() UTC() valueOf()

JS Error name message

JS Global decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() escape() eval() Infinity isFinite() isNaN() NaN Number() parseFloat() parseInt() String() undefined unescape()

JS JSON parse() stringify()

JS Math abs() acos() acosh() asin() asinh() atan() atan2() atanh() cbrt() ceil() cos() cosh() E exp() floor() LN2 LN10 log() LOG2E LOG10E max() min() PI pow() random() round() sin() sqrt() SQRT1_2 SQRT2 tan() tanh() trunc()

JS Number constructor isFinite() isInteger() isNaN() isSafeInteger() MAX_VALUE MIN_VALUE NEGATIVE_INFINITY NaN POSITIVE_INFINITY prototype toExponential() toFixed() toLocaleString() toPrecision() toString() valueOf()

JS OperatorsJS RegExp constructor compile() exec() g global i ignoreCase lastIndex m multiline n+ n* n? n{X} n{X,Y} n{X,} n$ ^n ?=n ?!n source test() toString() (x|y) . \w \W \d \D \s \S \b \B \0 \n \f \r \t \v \xxx \xdd \uxxxx

JS Statements break class continue debugger do…while for for…in for…of function if…else return switch throw try…catch var while

JS String charAt() charCodeAt() concat() constructor endsWith() fromCharCode() includes() indexOf() lastIndexOf() length localeCompare() match() prototype repeat() replace() search() slice() split() startsWith() substr() substring() toLocaleLowerCase() toLocaleUpperCase() toLowerCase() toString() toUpperCase() trim() valueOf()

浏览器兼容性

The compatibility table on this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Chrome Full support 1 Edge Full support 12 Firefox Full support 3.5 IE Full support 9 Opera Full support 10 Safari Full support 4 WebView Android Full support Yes Chrome Android Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support Yes
Experimental Chrome Full support 54 Edge Full support 17 Firefox Full support 49 IE No support No Opera Full support 39 Safari Full support 10 WebView Android Full support 54 Chrome Android Full support 54 Firefox Android Full support 49 Opera Android Full support 41 Safari iOS Full support 10 Samsung Internet Android Full support 6.0
Chrome Full support 1 Edge Full support 12 Firefox Full support 3.5 IE Full support 9 Opera Full support 10 Safari Full support 4 WebView Android Full support Yes Chrome Android Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support Yes
Chrome Full support 1 Edge Full support 12 Firefox Full support 3.5 IE Full support 9 Notes Opera Full support 10 Safari Full support 4 WebView Android Full support 1 Chrome Android Full support 18 Firefox Android Full support 4 Opera Android Full support 10.1 Safari iOS Full support 9 Samsung Internet Android Full support 1.0
Support on and Experimental Chrome Full support 29 Edge Full support ≤79 Firefox Full support 25 IE No support No Opera Full support 16 Safari No support No WebView Android Full support Yes Chrome Android Full support Yes Firefox Android ? Opera Android ? Safari iOS No support No Samsung Internet Android Full support Yes
Chrome Full support 1 Edge Full support 12 Firefox Full support 3.5 IE Full support 9 Opera Full support 10 Safari Full support 4 WebView Android Full support Yes Chrome Android Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support Yes
Chrome Full support 1 Edge Full support 12 Firefox Full support 3.5 IE Full support 9 Opera Full support 10 Safari Full support 4 WebView Android Full support Yes Chrome Android Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support Yes
Experimental Chrome Full support 54 Edge Full support 17 Firefox Full support 49 IE No support No Opera Full support 39 Safari Full support 10 WebView Android Full support 54 Chrome Android Full support 54 Firefox Android Full support 49 Opera Android Full support 41 Safari iOS Full support 10 Samsung Internet Android Full support 6.0
Chrome Full support 1 Edge Full support 12 Firefox Full support 3.5 IE Full support 9 Notes Opera Full support 10 Safari Full support 4 WebView Android Full support ≤37 Chrome Android Full support 18 Firefox Android Full support Yes Opera Android Full support 10.1 Safari iOS Full support 3.2 Samsung Internet Android Full support Yes
Chrome Full support 1 Edge Full support 12 Firefox Full support 3.5 IE Full support 9 Notes Opera Full support 10 Safari Full support 4 WebView Android Full support Yes Chrome Android Full support Yes Firefox Android Full support Yes Opera Android Full support 10.1 Safari iOS Full support 3.2 Samsung Internet Android Full support Yes
Chrome No support No Edge No support No Firefox Full support 78 IE No support No Opera No support No Safari Full support 14 WebView Android No support No Chrome Android No support No Firefox Android No support No Opera Android No support No Safari iOS Full support 14 Samsung Internet Android No support No

JavaScript

JS Array concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() forEach() from() includes() indexOf() isArray() join() keys() length lastIndexOf() map() pop() prototype push() reduce() reduceRight() reverse() shift() slice() some() sort() splice() toString() unshift() valueOf()

JS Boolean constructor prototype toString() valueOf()

JS Classes constructor() extends static super

JS Date constructor getDate() getDay() getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCFullYear() getUTCHours() getUTCMilliseconds() getUTCMinutes() getUTCMonth() getUTCSeconds() now() parse() prototype setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime() setUTCDate() setUTCFullYear() setUTCHours() setUTCMilliseconds() setUTCMinutes() setUTCMonth() setUTCSeconds() toDateString() toISOString() toJSON() toLocaleDateString() toLocaleTimeString() toLocaleString() toString() toTimeString() toUTCString() UTC() valueOf()

JS Error name message

JS Global decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() escape() eval() Infinity isFinite() isNaN() NaN Number() parseFloat() parseInt() String() undefined unescape()

JS JSON parse() stringify()

JS Math abs() acos() acosh() asin() asinh() atan() atan2() atanh() cbrt() ceil() cos() cosh() E exp() floor() LN2 LN10 log() LOG2E LOG10E max() min() PI pow() random() round() sin() sqrt() SQRT1_2 SQRT2 tan() tanh() trunc()

JS Number constructor isFinite() isInteger() isNaN() isSafeInteger() MAX_VALUE MIN_VALUE NEGATIVE_INFINITY NaN POSITIVE_INFINITY prototype toExponential() toFixed() toLocaleString() toPrecision() toString() valueOf()

JS OperatorsJS RegExp constructor compile() exec() g global i ignoreCase lastIndex m multiline n+ n* n? n{X} n{X,Y} n{X,} n$ ^n ?=n ?!n source test() toString() (x|y) . \w \W \d \D \s \S \b \B \0 \n \f \r \t \v \xxx \xdd \uxxxx

JS Statements break class continue debugger do…while for for…in for…of function if…else return switch throw try…catch var while

JS String charAt() charCodeAt() concat() constructor endsWith() fromCharCode() includes() indexOf() lastIndexOf() length localeCompare() match() prototype repeat() replace() search() slice() split() startsWith() substr() substring() toLocaleLowerCase() toLocaleUpperCase() toLowerCase() toString() toUpperCase() trim() valueOf()

Поддержка браузерами

The compatibility table on this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome для Android Firefox для Android Opera для Android Safari on iOS Samsung Internet
Экспериментальная Chrome Полная поддержка 54 Edge Полная поддержка 17 Firefox Полная поддержка 49 IE Нет поддержки Нет Opera Полная поддержка 39 Safari Полная поддержка 10 WebView Android Полная поддержка 54 Chrome Android Полная поддержка 54 Firefox Android Полная поддержка 49 Opera Android Полная поддержка 41 Safari iOS Полная поддержка 10 Samsung Internet Android Полная поддержка 6.0

JavaScript

JS Array concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() forEach() from() includes() indexOf() isArray() join() keys() length lastIndexOf() map() pop() prototype push() reduce() reduceRight() reverse() shift() slice() some() sort() splice() toString() unshift() valueOf()

JS Boolean constructor prototype toString() valueOf()

JS Classes constructor() extends static super

JS Date constructor getDate() getDay() getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCFullYear() getUTCHours() getUTCMilliseconds() getUTCMinutes() getUTCMonth() getUTCSeconds() now() parse() prototype setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime() setUTCDate() setUTCFullYear() setUTCHours() setUTCMilliseconds() setUTCMinutes() setUTCMonth() setUTCSeconds() toDateString() toISOString() toJSON() toLocaleDateString() toLocaleTimeString() toLocaleString() toString() toTimeString() toUTCString() UTC() valueOf()

JS Error name message

JS Global decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() escape() eval() Infinity isFinite() isNaN() NaN Number() parseFloat() parseInt() String() undefined unescape()

JS JSON parse() stringify()

JS Math abs() acos() acosh() asin() asinh() atan() atan2() atanh() cbrt() ceil() cos() cosh() E exp() floor() LN2 LN10 log() LOG2E LOG10E max() min() PI pow() random() round() sin() sqrt() SQRT1_2 SQRT2 tan() tanh() trunc()

JS Number constructor isFinite() isInteger() isNaN() isSafeInteger() MAX_VALUE MIN_VALUE NEGATIVE_INFINITY NaN POSITIVE_INFINITY prototype toExponential() toFixed() toLocaleString() toPrecision() toString() valueOf()

JS OperatorsJS RegExp constructor compile() exec() g global i ignoreCase lastIndex m multiline n+ n* n? n{X} n{X,Y} n{X,} n$ ^n ?=n ?!n source test() toString() (x|y) . \w \W \d \D \s \S \b \B \0 \n \f \r \t \v \xxx \xdd \uxxxx

JS Statements break class continue debugger do…while for for…in for…of function if…else return switch throw try…catch var while

JS String charAt() charCodeAt() concat() constructor endsWith() fromCharCode() includes() indexOf() lastIndexOf() length localeCompare() match() prototype repeat() replace() search() slice() split() startsWith() substr() substring() toLocaleLowerCase() toLocaleUpperCase() toLowerCase() toString() toUpperCase() trim() valueOf()

More Examples

Example

In this example, we demonstrate how whitespace may interfare with this property.

Get the node name of the last child node of a <div> element:

<!— Whitespace inside elements is considered as text, and text is considered as nodesIn this example, there is whitespace before <p>, before <span> and after <span>Therefore, the last child node of <div> is a #text node, and not the <span> element you expected —><div id=»myDIV»>  <p>Looks like first child</p>  <span>Looks like last Child</span></div> <script>var x = document.getElementById(«myDIV»).lastChild.nodeName;document.getElementById(«demo»).innerHTML = x;</script>

Example

However, if we remove the whitespace from the source, there are no #text nodes in <div>, which will make the <span> element the last child node:

<div id=»myDIV»><p>First child</p><span>Last Child</span></div> <script>var x = document.getElementById(«myDIV»).lastChild.nodeName;document.getElementById(«demo»).innerHTML = x; </script>

Example

Get the text of the last child node of a <select> element:

var x = document.getElementById(«mySelect»).lastChild.text;

More Examples

Example

Replace a <li> element in a list with a new <li> element:

// Create a new <li> elementvar elmnt = document.createElement(«li»);// Create a new text node called «Water» var textnode = document.createTextNode(«Water»);// Append the text node to <li>elmnt.appendChild(textnode);// Get the <ul> element with id=»myList»var item = document.getElementById(«myList»);// Replace the first child node (<li> with index 0) in <ul> with the newly created <li> elementitem.replaceChild(elmnt, item.childNodes);// Note: This example replaces the entire <li> element

Before removing:

  • Coffee
  • Tea
  • Milk

After removing:

  • Water
  • Tea
  • Milk

С этим читают