Nodelist

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()

Document Object Properties and Methods

The following properties and methods can be used on HTML documents:

Property / Method Description
activeElement Returns the currently focused element in the document
addEventListener() Attaches an event handler to the document
adoptNode() Adopts a node from another document
anchors Returns a collection of all <a> elements in the document that have a name attribute
applets Returns a collection of all <applet> elements in the document
baseURI Returns the absolute base URI of a document
body Sets or returns the document’s body (the <body> element)
close() Closes the output stream previously opened with document.open()
cookie Returns all name/value pairs of cookies in the document
charset Deprecated. Use characterSet instead. Returns the character encoding for the document
characterSet Returns the character encoding for the document
createAttribute() Creates an attribute node
createComment() Creates a Comment node with the specified text
createDocumentFragment() Creates an empty DocumentFragment node
createElement() Creates an Element node
createEvent() Creates a new event
createTextNode() Creates a Text node
defaultView Returns the window object associated with a document, or null if none is available.
designMode Controls whether the entire document should be editable or not.
doctype Returns the Document Type Declaration associated with the document
documentElement Returns the Document Element of the document (the <html> element)
documentMode Returns the mode used by the browser to render the document
documentURI Sets or returns the location of the document
domain Returns the domain name of the server that loaded the document
domConfig Obsolete. Returns the DOM configuration of the document
embeds Returns a collection of all <embed> elements the document
execCommand() Invokes the specified clipboard operation on the element currently having focus.
forms Returns a collection of all <form> elements in the document
fullscreenElement Returns the current element that is displayed in fullscreen mode
fullscreenEnabled() Returns a Boolean value indicating whether the document can be viewed in fullscreen mode
getElementById() Returns the element that has the ID attribute with the specified value
getElementsByClassName() Returns a HTMLCollection containing all elements with the specified class name
getElementsByName() Returns a HTMLCollection containing all elements with a specified name
getElementsByTagName() Returns a HTMLCollection containing all elements with the specified tag name
hasFocus() Returns a Boolean value indicating whether the document has focus
head Returns the <head> element of the document
images Returns a collection of all <img> elements in the document
implementation Returns the DOMImplementation object that handles this document
importNode() Imports a node from another document
inputEncoding Returns the encoding, character set, used for the document
lastModified Returns the date and time the document was last modified
links Returns a collection of all <a> and <area> elements in the document that have a href attribute
normalize() Removes empty Text nodes, and joins adjacent nodes
normalizeDocument() Removes empty Text nodes, and joins adjacent nodes
open() Opens an HTML output stream to collect output from document.write()
querySelector() Returns the first element that matches a specified CSS selector(s) in the document
querySelectorAll() Returns a static NodeList containing all elements that matches a specified CSS selector(s) in the document
readyState Returns the (loading) status of the document
referrer Returns the URL of the document that loaded the current document
removeEventListener() Removes an event handler from the document (that has been attached with the addEventListener() method)
renameNode() Renames the specified node
scripts Returns a collection of <script> elements in the document
strictErrorChecking Sets or returns whether error-checking is enforced or not
title Sets or returns the title of the document
URL Returns the full URL of the HTML document
write() Writes HTML expressions or JavaScript code to a document
writeln() Same as write(), but adds a newline character after each statement

JS Учебник

JS ГлавнаяJS ВведениеJS УстановкаJS ВыводJS СинтаксисJS ЗаявленияJS КомментарииJS ПеременныеJS ОператорыJS АрифметикаJS ПрисваиванияJS Типы данныхJS ФункцииJS ОбъектыJS ОбластьJS СобытияJS СтрокиJS Методы строкJS ЧислаJS Методы чиселJS МассивыJS Методы массиваJS Сортировка массиваJS Итерация массиваJS ДатыJS Формат датыJS Метод получения датJS Методы набора…JS Математические…JS Случайные числаJS БулевыJS Сравнение…JS Заявления if…elseJS Заявление switchJS Цикл forJS Цикл whileJS Заявление break…JS Преобразование…JS Битовые…JS Регулярные выраженияJS ОшибкиJS ОтладчикJS ПодъемныйJS СтрогийJS Ключевое слово thisJS Руководство стиляJS ПрактикаJS Распространенные ошибкиJS ЭффективностьJS Зарезервированные словаJS ВерсииJS Версия ES5JS Версия ES6JS JSON

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.

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()

JS Tutorial

JS HOMEJS IntroductionJS Where ToJS OutputJS StatementsJS SyntaxJS CommentsJS VariablesJS OperatorsJS ArithmeticJS AssignmentJS Data TypesJS FunctionsJS ObjectsJS EventsJS StringsJS String MethodsJS NumbersJS Number MethodsJS ArraysJS Array MethodsJS Array SortJS Array IterationJS DatesJS Date FormatsJS Date Get MethodsJS Date Set MethodsJS MathJS RandomJS BooleansJS ComparisonsJS ConditionsJS SwitchJS Loop ForJS Loop WhileJS BreakJS Type ConversionJS BitwiseJS RegExpJS ErrorsJS ScopeJS HoistingJS Strict ModeJS this KeywordJS LetJS ConstJS Arrow FunctionJS DebuggingJS Style GuideJS Best PracticesJS MistakesJS PerformanceJS Reserved WordsJS VersionsJS Version ES5JS Version ES6JS JSON

Description

DataTables will add a number of elements around the table to both control the table and show additional information about it. The position of these elements on screen are controlled by a combination of their order in the document (DOM) and the CSS applied to the elements. This parameter is used to control their ordering and additional mark-up surrounding them in the DOM.

Each table control element in DataTables has a single letter associated with it, and that letter it used in this configuration option to indicate where that element will appear in the document order.

Options

The built-in table control elements in DataTables are:

  • — ength changing input control
  • — iltering input
  • — The able!
  • — Table nformation summary
  • — agination control
  • — pocessing display element

Each option can be specified multiple times (with the exception of the table itself), which can be used to have table controls both above and below the table. DataTables will automatically synchronise these multiple controls.

In addition to the above control options, there are two constants DataTables understands (note that these two options are deprecated in 1.10 and will be removed in 1.11 along side the separation of the option into its own theme file):

  • — jQueryUI theme «header» classes ()
  • — jQueryUI theme «footer» classes ()

Markup

Further to these options, you can also specify additional elements to be inserted into the document, which can be used for styling / nesting of the control elements. To add tags, the following syntax is expected:

  • and — div element
  • and — div with a class
  • and — div with an ID
  • and — div with an ID and a class

Styling

The styling libraries that DataTables supports will override the default value of the parameter and replace it with a value that is suitable for their layout system. For example the Bootstrap integration makes use of Bootstrap’s grid layout.

The defaults for the styling integrations are:

Bootstrap 3:

Bootstrap 4:

Foundation:

jQuery UI:

Semantic UI:

Plug-ins

DataTables feature plug-ins can be developed to add additional features to DataTables and often will make use of this option, adding new letters to the DataTables core features. For example Buttons adds the option to to specify where table control buttons should be inserted into the table.

The following extensions can be initialised through the option:

  • — Buttons
  • — ColReorder
  • — Scroller
  • — SearchPanes

Future development

Note, I am aware that this is the most complex option in DataTables and it takes a fair amount of understanding, particularly when using the styling integration options! The plan is to revamp this option in 1.11 to make it easier to use.

Чем DOM не является

В приведенном выше примере кажется, что DOM является отображением 1: 1 исходного HTML-документа. Однако, как я уже говорил, есть различия. Чтобы полностью понять, что такое DOM, нам нужно взглянуть на то, чем он не является.

DOM не является копией исходного HTML

Хотя DOM создан из HTML-документа, он не всегда точно такой же. Есть два случая, в которых DOM может отличаться от исходного HTML.

1. Когда HTML содержит ошибки разметки

DOM — это интерфейс доступа к действительных (то есть уже отображаемым) элементам документа HTML. В процессе создания DOM, браузер сам может исправить некоторые ошибки в коде HTML.

Рассмотрим в качестве примера этот HTML-документ:

<!doctype html>
<html>
Hello, world!
</html>

В документе отсутствуют элементы    и   , что является обязательным требованием для HTML. Но если мы посмотрим на получившееся дерево DOM, то увидим, что это было исправлено:

  • html
    • head
    • body
      • Hello, world!

2. Когда DOM модифицируется кодом Javascript

Помимо того, что DOM является интерфейсом для просмотра содержимого документа HTML, он сам также может быть изменен.

Мы можем, например, создать дополнительные узлы для DOM, используя Javascript.

var newParagraph = document.createElement("p");
var paragraphContent = document.createTextNode("I'm new!");
newParagraph.appendChild(paragraphContent);
document.body.appendChild(newParagraph);

Этот код изменит DOM, но изменения не отобразятся в документе HTML .

DOM — это не то, что вы видите в браузере (то есть, дерево рендеринга)

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

Поскольку дерево рендеринга имеет отношение только к тому, что отображается, оно исключает элементы, которые визуально скрыты. Например, элементы, у которых есть стили с display: none.

<!doctype html>
<html lang="en">
  <head></head>
  <body>
    <h1>Hello, world!</h1>
    <p style="display: none;">How are you?</p>
  </body>
</html>

DOM будет включать элемент :

  • html
    • head
    • body
      • h1
      • p

Однако дерево рендеринга и, следовательно, то, что видно в окне просмотра, не будет включено в этот элемент.

  • html
    • body
      • h1

DOM — это не то, что отображается в DevTools

Это различие немного меньше, потому что инспектор элементов DevTools обеспечивает самое близкое приближение к DOM, которое мы имеем в браузере. Однако инспектор DevTools содержит дополнительную информацию, которой нет в DOM.

Лучший пример этого — псевдоэлементы CSS. Псевдоэлементы, созданные с использованием селекторов ::before и ::after, являются частью CSSOM и дерева рендеринга, но технически не являются частью DOM. Это связано с тем, что DOM создается только из исходного HTML-документа, не включая стили, примененные к элементу.

Несмотря на то, что псевдоэлементы не являются частью DOM, они есть в нашем инспекторе элементов devtools.

JS Tutorial

JS HOMEJS IntroductionJS Where ToJS OutputJS StatementsJS SyntaxJS CommentsJS VariablesJS OperatorsJS ArithmeticJS AssignmentJS Data TypesJS FunctionsJS ObjectsJS EventsJS StringsJS String MethodsJS NumbersJS Number MethodsJS ArraysJS Array MethodsJS Array SortJS Array IterationJS DatesJS Date FormatsJS Date Get MethodsJS Date Set MethodsJS MathJS RandomJS BooleansJS ComparisonsJS ConditionsJS SwitchJS Loop ForJS Loop WhileJS BreakJS Type ConversionJS BitwiseJS RegExpJS ErrorsJS ScopeJS HoistingJS Strict ModeJS this KeywordJS LetJS ConstJS Arrow FunctionJS DebuggingJS Style GuideJS Best PracticesJS MistakesJS PerformanceJS Reserved WordsJS VersionsJS Version ES5JS Version ES6JS JSON

Definition and Usage

The lastChild property returns the last child node of the specified node, as a Node object.

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

Note: Whitespace inside elements is considered as text, and
text is considered as nodes (See «More Examples»).

This property is read-only.

Tip: Use the element.childNodes
property to return any child node of a specified node.

Tip: To return the first child node of a specified node, use
the firstChild 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()

Дерево и узлы DOM

Все элементы в DOM определяются как узлы. Существует множество типов узлов, но есть три основных, с которыми вы будете работать чаще всего:

  1. Узел элемента
  2. Текстовый узел
  3. Узел комментария

Когда элемент HTML является элементом в DOM, он называется узлом элемента. Любой одиночный текст вне элемента является текстовым узлом, а комментарий HTML – узлом комментария. Помимо этих трех типов узлов, сам объект document – это узел документа, который является корневым узлом всех остальных узлов.

DOM состоит из древовидной структуры вложенных узлов, которая часто называется деревом DOM. Вы наверняка знаете, что собой представляет генеалогическое дерево – это схематичное представление родственных связей, которое состоит из родителей, детей и ближайших родственников. Узлы в DOM также называются родительскими и дочерними в зависимости от их отношения к другим узлам.

Для примера создайте файл nodes.html. добавьте в него текстовый узел, а также узлы комментария и элемента.

Узел элемента html является родительским. head и body – дочерние узлы html. body содержит три дочерних узла, и все они находятся на одном уровне – тип узла не влияет на уровень вложения.

Терминология HTML

Понимание терминов HTML и JavaScript критически необходимо для работы с DOM. Давайте вкратце рассмотрим основные термины.

Посмотрите на этот элемент HTML:

В нем присутствует анкор, который является ссылкой на index.html.

  • a – тег
  • href – атрибут
  • html – значение атрибута
  • Home – текст.

Все, что находится между открывающимся и закрывающимся тегами, составляет HTML-элемент.

Вернемся к файлу index.html из предыдущего мануала:

Самый простой способ доступа к элементу с JavaScript – это атрибут id. Давайте добавим указанную выше ссылку в файл index.html с id=»nav».

Загрузите (или обновите) страницу в окне браузера и посмотрите на DOM, чтобы убедиться, что код был обновлен.

Затем используйте метод getElementById() для доступа ко всему элементу. В консоли введите следующее:

Метод getElementById() извлечет весь элемент. Теперь вместо того, чтобы вводить этот объект и метод каждый раз, когда вам нужно получить доступ к ссылке nav, вы можете поместить элемент в переменную, чтобы с ним было проще работать.

Переменная navLink содержит анкор. Здесь можно легко изменять атрибуты и значения. Например, чтобы изменить место ссылки, измените атрибут href:

Также можно изменить текст, переназначив свойство textContent:

Теперь, просмотрев этот элемент в консоли или проверив тег Elements, вы увидите, как он обновился.

Изменения отобразятся и на фронт-энде.

Обновление страницы вернет все исходные значения.

На этом этапе вы должны понимать, как использовать метод document для доступа к элементу, как присвоить элемент переменной и как изменить свойства и значения в элементе.

JS Tutorial

JS HOMEJS IntroductionJS Where ToJS OutputJS StatementsJS SyntaxJS CommentsJS VariablesJS OperatorsJS ArithmeticJS AssignmentJS Data TypesJS FunctionsJS ObjectsJS EventsJS StringsJS String MethodsJS NumbersJS Number MethodsJS ArraysJS Array MethodsJS Array SortJS Array IterationJS DatesJS Date FormatsJS Date Get MethodsJS Date Set MethodsJS MathJS RandomJS BooleansJS ComparisonsJS ConditionsJS SwitchJS Loop ForJS Loop WhileJS BreakJS Type ConversionJS BitwiseJS RegExpJS ErrorsJS ScopeJS HoistingJS Strict ModeJS this KeywordJS LetJS ConstJS Arrow FunctionJS DebuggingJS Style GuideJS Best PracticesJS MistakesJS PerformanceJS Reserved WordsJS VersionsJS Version ES5JS Version ES6JS JSON

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;

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *