DOM elements - garevna/js-course GitHub Wiki

🎓 Элементы DOM

⤵️

Методы

↪️ appendChild ↪️removeChild
↪️ insertBefore ↪️ replaceChild
↪️ insertAdjacentHTML ↪️ insertAdjacentElement
↪️ setAttribute ↪️ getAttribute
↪️ getBoundingClientRect ↪️ scrollIntoView
↪️ addEventListener ↪️ removeEventListener

✅ appendChild()
⤴️ ⤵️

Добавляет элементу дочерний элемент

☕ 1️⃣

<body>
    <div id="demo">
        <section></section>
        <figure></figure>
    </div>
</body>
var section = document.createElement ( "section" )
section.innerHTML = "Hello"
document.querySelector ( "#demo" ).appendChild ( section )

Результат:

<body>
    <div id="demo">
        <section>Hello</section>
    </div>
</body>

☕ 2️⃣

var style = document.createElement ( 'style' )
document.head.appendChild ( style )
style.innerText = `p { color: red; }`

style.sheet.cssRules[0]          // объект
style.sheet.cssRules[0].cssText  // "p { color: red; }"

style.appendChild (
    document.createTextNode (
        `div { color: blue; }`
    ) 
)

Результат:

<head>
    <style>
        p { color: red; }
        div { color: blue; }
    </style>
</head>

☕ 3️⃣

var script = document.createElement ( 'script' )
script.appendChild (
    document.createTextNode (
        `alert ( "Hello" )`
    )
)
document.body.appendChild ( script )

✅ removeChild()
⤴️ ⤵️

Удаление элемента

Метод возвращает ссылку на удаленный элемент

( это означает, что элемент удален со страницы, но

⚠️ Удалить элемент может только его непосредственный родитель

☕ 4️⃣

<body>
    <div id="demo">
        <section id="section"></section>
        <figure class="figure"></figure>
    </div>
</body>
var section = document.querySelector ( "#section" )
var removed = section.parentNode.removeChild ( section )
console.dir ( removed )  // ► section#section

var figure = document.querySelector ( ".figure" )
figure.appendChild ( removed )
<body>
    <div id="demo">
        <figure class="figure">
            <section id="section"></section>
        </figure>
    </div>
</body>

✅ insertBefore()
⤴️ ⤵️

☕ 5️⃣

function addElement ( tagName, container ) {
    var _container = 
        container && container.nodeType === 1 ? 
           container : document.body
    return _container.appendChild (
         document.createElement ( tagName )
    )
}

var main = addElement ( "main" )
var section = addElement ( "section", main )
var figure = addElement ( "figure", main )

main.insertBefore ( document.createElement ( "p" ), section )

✅ insertAdjacentHTML()
⤴️ ⤵️

☕ 6️⃣

Используя функцию addElement из предыдущего примера, вставим на страницу элементы main, section и figure:

<body>
    <main>
        <section></section>
        <figure></figure>
    </main>
</body>

А теперь выполним следующий код в консоли:

section.insertAdjacentHTML ( `beforeBegin`, `<p>Hello</p>` )
section.insertAdjacentHTML ( `afterBegin`, `<p>Let's work</p>` )
section.insertAdjacentHTML ( `beforeEnd`, `<p>I've finished</p>` )
section.insertAdjacentHTML ( `afterEnd`, `<p>Bye</p>` )

Результат во вкладке Elements:

<body>
    <main>
        <p>Hello</p>
        <section>
            <p>Let's work</p>
            <p>I've finished</p>
        </section>
        <p>Bye</p>
        <figure></figure>
    </main>
</body>

✅ insertAdjacentElement()
⤴️ ⤵️

☕ 7️⃣

<body>
    <main>
        <section id="demo">
        </section>
        <figure></figure>
    </main>
</body>
document.getElementById ( "demo" )
    .insertAdjacentElement( 
        "beforeend",
        document.createElement ( "p" )
    )
document.querySelector ( "figure" )
    .insertAdjacentElement( 
        "afterend",
        document.createElement ( "h3" )
    )
document.querySelector ( "#demo" )
    .insertAdjacentElement( 
        "beforebegin",
        document.createElement ( "img" )
    )
document.getElementsByTagName ( "figure" )[0]
    .insertAdjacentElement( 
        "afterbegin",
        document.createElement ( "li" )
    )

Результат во вкладке Elements:

<body>
    <main>
        <img>
        <section id="demo">
            <p></p>
        </section>
        <figure>
            <li></li>
        </figure>
        <h3></h3>
    </main>
</body>

Свойства

childNodes

Объект NodeList

☕ 8️⃣

🔗 w3schools


children

Объект HTMLCollection

parentNode

Ссылка на родительский элемент ( контейнер, в котором находится элемент )

☕ 9️⃣

<body>
    <div id="demo">
        <section id="section"></section>
        <figure></figure>
    </div>
</body>
var section = document.querySelector ( "#section" )
console.dir ( section.parentNode )  // ► div#demo
on + тип события

Все свойства элементов DOM, начинающиеся на on, являются потенциальными ссылками на обработчика соответствующего события

Изначально они имеют значение null

☕ 🔟

var section = document.body.appendChild (
     document.createElement ( 'section' )
)
section.innerHTML = "<h3>Hello</h3>"

for ( var prop in section ) {
     if ( prop.indexOf ( 'on' ) !== 0 ) continue
     console.info ( `Event: ${prop.slice(2)}` )
}

Дополнительно

setAttribute | getAttribute

document.body.setAttribute ( 'title', 'Hello' )

console.info (
    document.body.getAttribute ( 'title' )
)

getBoundingClientRect

var div = document.body.appendChild (
    document.createElement ( "div" )
)
div.setAttribute ( 'style', `
    width: 200px;
    height: 200px;
    border: solid 1px blue;
` )

console.info (
    div.getBoundingClientRect ()
)

backgroundImage

var btn = document.createElement ( 'button' )
btn.innerText = "OK"
btn.style = `
    background-image: url(https://cdn2.iconfinder.com/data/icons/user-23/512/User_Yuppie_2.png);
    background-size: contain;
    background-repeat: no-repeat;
    background-position: left center;
    padding: 5px 10px 5px 30px;
`
document.body.appendChild ( btn )


🔗 w3schools

⚠️ **GitHub.com Fallback** ⚠️