Summary of “JavaScript in the browser”. Part 2
The element.children
DOM property returns a collection of child, that is, nested, DOM elements.
Creating an element and adding it to the DOM tree:
var list = document.querySelector('.cards');
// Creating a new element
var card = document.createElement('li');
card.classList.add('card');
// After calling this method,
// a new element is rendered on page
list.appendChild(card);
Here’s what happens with the markup after calling appendChild
:
<!-- Initial markup state -->
<ul class="cards">
<li class="card">Existing element</li>
</ul>
<!-- State after calling appendChild -->
<ul class="cards">
<li class="card">Existing element</li>
<li class="card">Added element</li>
</ul>
Working with the text content of the element:
// HTML
<p>I’m a <em>text element</em>.</p>
// JS
var p = document.querySelector('p');
console.log(p.textContent);
// Logs 'I’m a text element.'
p.textContent = 'Now I have new contents.';
console.log(p.textContent);
// Logs 'Now I have new contents.'
// In HTML, the tag content will change
<p>Now I have new contents.</p>
Working with images:
// Creating an image
var picture = document.createElement('img');
// Adding picture address
picture.src = 'images/picture.jpg';
// Adding alternative text
picture.alt = 'Unsinkable selfie stick';
// Adding the image to the end of the parent element
element.appendChild(picture);
Continue