Front/JavaScript

Javascript-DOM-API-cheatsheet

oodada 2023. 9. 11. 21:44

DOM

Dom (Document Object Modal) 이란
HTML 문서를 객체로 표현한 것으로 JS에서 HTML을 제어할 수 있게 해줍니다.

Node vs Element

노트(Node) : HTML 요소, 텍스트, 주석 등 모든 것을 의미
요소(Element) : HTML 요소를 의미

DOM node 란?

DOM Element Traversal

// 지정된 id값을 가진 요소를 반환
document.getElementById("someid");

// 지정된 클래스 이름을 가진 모든 하위 요소의 개체를 반환
document.getElementsByClassName("someclass");

// 지정된 태그 이름을 가진 요소의 HTML 모음을 반환
document.getElementsByTagName("LI");

// 지정된 class와 일치하는 문서 내의 첫 번째 요소를 반환
document.querySelector(".someclass");

// 문서 내의 요소 목록을 반환 (문서 노드의 깊이 우선 사전 순서 횡단 사용)
document.querySelectorAll("div.note, div.alert");

부모/자식 노드 선택하기

// 자식 노드 가져오기
var stored = document.getElementById("someid");
var children = stored.childNodes;

// 부모 노드 가져오기
var parental = children.parentNode;

새로운 DOM Elements 생성

// create new elments
var newHeading = document.createElement("h1");
var newParagraph = document.createElement("p");

// create text nodes for new elements
var h1Text = document.createTextNode("This is a nice header text!");
var pText = document.createTextNode("This is a nice paragraph text!");

// attach new text nodes to new elements
newHeading.appendChild(h1Text);
newParagraph.appendChild(pText);

// elements are now created and ready to be added to the DOM.

Add Elements to the DOM

// grab element on page you want to add stuff to
var firstHeading = document.getElementById("firstHeading");

// add both new elements to the page as children to the element we stored in firstHeading.
firstHeading.appendChild(newHeading);
firstHeading.appendChild(newParagraph);

// can also insert before like so

// get parent node of firstHeading
var parent = firstHeading.parentNode;

// insert newHeading before FirstHeading
parent.insertBefore(newHeading, firstHeading);

Suppose you have the following HTML:

<div id="box1"><p>Some example text</p></div>
<div id="box2"><p>Some example text</p></div>

You can insert another snippet of HTML between #box1 and #box2:

var box2 = document.getElementById("box2");
box2.insertAdjacentHTML("beforebegin", "<div><p>This gets inserted.</p></div>");

// beforebegin - The HTML would be placed immediately before the element, as a sibling.
// afterbegin - The HTML would be placed inside the element, before its first child.
// beforeend - The HTML would be placed inside the element, after its last child.
// afterend - The HTML would be placed immediately after the element, as a sibling.

Add/Remove/Toggle/Check Classes

// grab element on page you want to use
var firstHeading = document.getElementById("firstHeading");

// will remove foo if it is a class of firstHeading
firstHeading.classList.remove("foo");

// will add the class 'anotherClass' if one does not already exist
firstHeading.classList.add("anotherclass");

// add or remove multiple classes
firstHeading.classList.add("foo", "bar");
firstHeading.classList.remove("foo", "bar");

// if visible class is set remove it, otherwise add it
firstHeading.classList.toggle("visible");

// will return true if it has class of 'foo' or false if it does not
firstHeading.classList.contains("foo");

Using template literals

<body></body>
function render(props) {
  return `
            <div class="container"> 
                <h1> ${props.name} </h1>
            </div>
        `;
}

document.body.innerHTML = render("John");

Other node methods

// Creates newNode as a copy (clone) of node. If bool is true, the clone includes clones of all the child nodes of the original.

newNode = node.cloneNode(bool);

// Removes the child oldNode from node.
node.removeChild(oldNode):

// Replaces the child node oldNode of node with newNode.
node.replaceChild(newNode, oldNode)

// Retrieves the value of the attribute with the name attribute
node.getAttribute('attribute')

// Sets the value of the attribute with the name attribute to value
node.setAttribute('attribute', 'value')

// Reads the type of the node (1 = element, 3 = text node)
node.nodeType

// Reads the name of the node (either element name or #textNode)
node.nodeName

// Reads or sets the value of the node (the text content in the case of text nodes)
node.nodeValue

Events

Inline event handling

<a href="site.com" onclick="dosomething();">A link</a>

DOM on-event handling

window.onload = () => {
  //window loaded
};

const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
  //.. do something
};

Using addEventListener()

window.addEventListener("load", onLoad);
window.removeEventListener("load", onLoad);

Custom events

//A CustomEventInit dictionary, having the following fields: "detail", optional and defaulting to null, of type any, that is an event-dependent value associated with the event.
event = new CustomEvent(typeArg, customEventInit);

Dispatching

var event = new Event("build");
// Listen for the event.
elem.addEventListener(
  "build",
  function(e) {
    /* ... */
  },
  false
);
// Dispatch the event.
elem.dispatchEvent(event);

Date and time

//Sun Nov 18 2018 23:18:58 GMT+0530 (India Standard Time)
var d = new Date();
//1542563338408 miliseconds passed since 1970
Number(d);
Date("2017-06-23"); // date declaration
Date("2017"); // is set to Jan 01
Date("2017-06-23T12:00:00-09:45"); // date - time YYYY-MM-DDTHH:MM:SSZ
Date("June 23 2017"); // long date format
Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)"); // time zone

var d = new Date();
a = d.getDay(); // getting the weekday

getDate(); // day as a number (1-31)
getDay(); // weekday as a number (0-6)
getFullYear(); // four digit year (yyyy)
getHours(); // hour (0-23)
getMilliseconds(); // milliseconds (0-999)
getMinutes(); // minutes (0-59)
getMonth(); // month (0-11)
getSeconds(); // seconds (0-59)
getTime(); // milliseconds since 1970

var d = new Date();
d.setDate(d.getDate() + 7); // adds a week to a date

setDate(); // day as a number (1-31)
setFullYear(); // year (optionally month and day)
setHours(); // hour (0-23)
setMilliseconds(); // milliseconds (0-999)
setMinutes(); // minutes (0-59)
setMonth(); // month (0-11)
setSeconds(); // seconds (0-59)
setTime(); // milliseconds since 1970)

'Front > JavaScript' 카테고리의 다른 글

연산자(Operator) - javascript 기본  (0) 2023.09.11
JS데이터(JSData) - javascript 기본  (1) 2023.09.11
Javascript 입문  (0) 2023.09.11
06. 객체  (0) 2020.08.19
05. 함수  (0) 2020.08.19
티스토리 친구하기