React/DOM
DOM (2)
WebDevLee
2021. 10. 23. 12:47
이 글은 자바스크립트의 DOM(Document Object Model)에 관한
기본 개념 및 문법을 정리하기 위해 작성하였습니다.
< The document keyword >
The document keyword allows you to access the root node of the DOM free.
- Before you can access a specific element in the page, first you must access the document structure itself.
ex)
// If you wanted to access <body> element in your script
document.body // This will return body element of that DOM.
< Tweak an Element >
To access and set the contents of an element using the keyword .innerHTML
ex)
// reassigns the inner HTML of the body element to the text ‘The cat loves the dog’:
document.body.innerHTML = 'The cat loves the dog.';
// assigns(add) an h2 element as a child inside the <body> element:
document.body.innerHTML = '<h2>This is a heading</h2>';
< Select and Modify Elements >
To access a specific element with CSS Selectors(tag, class, ID, etc...)
- In general, Use this :
1) .querySelector()
2) .querySelectorAll()
3) .getElementById()
4) etc
ex)
document.querySelector('p'); // returns the first P element
document.getElementById('bio').innerHTML = 'The description';
// Select the first element with an id of 'bio' and set its .innerHTML to the text 'The description'
< Style an Element >
To style element using .style property of a DOM element.
<Syntax>
element.style.property
- Unlike CSS, the DOM style property does not use a hyphen(-) : background-color -> backgroundColor
ex)
// example 1
let blueElement = document.querySelector('.blue');
blueElement.style.backgroundColor = 'blue';
// example 2
document.querySelector('.blue').style.fontFamily = 'Roboto';
< Create and Insert Elements >
To create element using .createElement(tagName) and
To add a element using .appendChild()
- .createElement(tagName) method creates a new empty element based on the tag name.
(However, it does not append it to the document. It creates an empty element with no inner HTML) - .appendChild() method adds a child element as the last child of the parent that already exists.
ex)
let paragraph = document.createElement('p');
paragraph.id = 'info';
paragraph.innerHTML = 'The text inside the paragraph';
document.body.appendChild(paragraph);
< Remove an Element >
To remove element using .removeChild() method.
ex)
let paragraph = document.querySelector('p');
document.body.removeChild(paragraph);
< Traversing the DOM >
To get the element's parent node or child node.
- .parentNode : return the node's parent node.
- .parentElement : return the node's parent element (if not exist, return null)
- .children : return a list of the element's children (if has no children, return null)
+. .firstChild property : return the first child element.