document - garevna/js-course GitHub Wiki
воспользуемся рекурсивной функцией showProto:
function showProto ( elem ) {
var proto = elem.__proto__
if ( !proto ) return
console.info ( proto.constructor.name )
showProto ( proto )
}для получения цепочки прототипов объекта document
showProto ( document )Результат:
• HTMLDocument
• Document
• Node
• EventTarget
• Object
Объект document включает две структурные части:
• document.head
• document.body
Если применить функцию showProto к document.head:
showProto ( document.head )то мы получим такую цепочку протипов:
• HTMLHeadElement
• HTMLElement
• Element
• Node
• EventTarget
• Object
Применим функцию showProto к document.body:
showProto ( document.body )цепочка протипов будет такой:
• HTMLBodyElement
• HTMLElement
• Element
• Node
• EventTarget
• Object
| document | document.head | document.body |
|---|---|---|
| HTMLHeadElement | HTMLBodyElement | |
| HTMLDocument | HTMLElement | HTMLElement |
| Document | Element | Element |
| Node | Node | Node |
| EventTarget | EventTarget | EventTarget |
| Object | Object | Object |
| Свойство | Содержание |
|---|---|
| ✅ document.head | HTMLHeadElement |
| ✅ document.body | HTMLBodyElement |
| ✅ document.doctype | строка |
| ✅ document.URL | строка |
| ✅ document.location | объект |
| ✅ document.images | HTMLCollection |
| ✅ document.forms | HTMLCollection |
| ✅ document.links | HTMLCollection |
| ✅ document.scripts | HTMLCollection |
| ✅ document.styleSheets | StyleSheetList |
| ✅ document.cookie | строка |
| ✅ document.cookie | строка |
| ✅ document.lastModified | строка ( '09/30/2018 11:00:15' ) |
| ... |
☕ document.scripts
for ( var script of document.scripts )
console.log ( script.innerText )☕ document.styleSheets
for ( var sheet of document.styleSheets ) {
for ( var rule of sheet.cssRules ) {
console.warn ( rule.selectorText )
console.info ( rule.cssText )
}
}Выполним код в консоли:
for ( var prop in document )
prop.indexOf ( "on" ) === 0 ?
console.info ( prop.slice(2) ) : ""Мы получим длинный перечень событий объекта document
по умолчанию эти значениями этих свойств будет null
☕ 1
например, присвойте свойству onmouseover объекта document ссылку на функцию:
document.onmouseover = function ( event ) {
console.info ( `${event.clientX} : ${event.clientY}` )
} Создает элемент DOM и возвращает ссылку на него
Аргументом метода является строка, содержащая имя тега html-элемента ( регистр не имеет значения )
Если переданная строка не соответствует никакому тегу в спецификации языка html, то созданный элемент будет иметь класс HTMLUnknownElement
☕ 2
var style = document.createElement ( 'style' )
style.appendChild (
document.createTextNode (
`section { border: inset 1px; }`
)
)
console.log ( style )☕ 3
style.appendChild (
document.createTextNode (
`div { color: blue; }`
)
)Для поиска элементов на странице у объекта document есть несколько методов:
ищет элемент по его атрибуту id
Возвращают коллецию html-элементов ( итерабельный объект класса HTMLCollection ) либо по имени тега, либо по имени класса, либо по значению атрибута name
☕ 4
Разметка
<body>
<main name="main">
<section>
<div class="content"></div>
<figure class="content"></figure>
</section>
</main>
</body>JS
document
.getElementsByName("main")[0]
.getElementsByTagName("section")[0]
.getElementsByClassName("content")Результат:
▼ HTMLCollection(2) [div.content, figure.content]
► 0: div.content
► 1: figure.content
length: 2
► __proto__: HTMLCollectionВозвращает первый найденный элемент по указанному селектору
☕ 5
<body>
<h3 id="demo">demo</h3>
<section>
<div title="figure">figure</div>
<figure class="promoClass">promoClass</figure>
</section>
<input type="number">
<input type="color">
</body>document.querySelector ( "section" )
document.querySelector ( "#demo" )
document.querySelector ( ".promoClass" )
document.querySelector ( "[type='number']" )
document.querySelector ( "[title]" )Возвращает итерабельный объект класса NodeList, содержащий все элементы, соответствующие указанному селектору