๐Ÿ‹ Selecting, Creating and Deleting elements

hayoungยท2023๋…„ 3์›” 15์ผ
0

JavaScript-DOM

๋ชฉ๋ก ๋ณด๊ธฐ
1/5
post-thumbnail

JavaScript๋ฅผ ๋ฐฐ์šฐ๋ฉด์„œ ๋…ธ์…˜์— ํ•„๊ธฐํ•ด์™”๋Š”๋ฐ, velog๋ฅผ ํ†ตํ•ด ํ”Œ๋žซํผ์„ ๋ณด์—ฌ์ง€๋Š” ๊ณต๊ฐ„์œผ๋กœ ์˜ฎ๊ฒจ ์ข€ ๋” ์˜ˆ์˜๊ฒŒ ๋‚จ๊ฒจ์„œ ์Šค์Šค๋กœ ๋ณต์Šตํ•˜๊ณ  ์‹ถ์–ด์ง€๊ฒŒ ๊ธฐ๋ก์„ ์Œ“์•„๊ฐ€๊ณ  ์‹ถ๋‹ค. ์˜ค๋Š˜๋ถ€ํ„ฐ ์‹œ์ž‘๐Ÿฆ•

1. ๐Ÿ˜Selecting elements

์š”์†Œ ์„ ํƒํ•˜๊ธฐ

console.log(document.documentElement); //๋ฌธ์„œ ์ „์ฒด๋ฅผ ์„ ํƒ 
console.log(document.head); //head๋ฅผ ์„ ํƒ
console.log(document.body); //body๋ฅผ ์„ ํƒ

/* ๊ฐ€์žฅ ๋ณดํŽธ์ ์ธ ๋ฐฉ๋ฒ• */
console.log(document.querySelector(".header")); //header class ์„ ํƒ
const allSections = document.querySelectorAll(".section");
console.log(allSections); //section class ์ „์ฒด๋ฅผ nodeList๋กœ ๋ฐ˜ํ™˜ํ•จ

/* ๋‹ค๋ฅธ ๋ฐฉ๋ฒ• */
console.log(document.getElementById("section--1")); //section--1 id ์„ ํƒ
const allButtons = document.getElementsByTagName("button");
console.log(allButtons); //button tag ์ „์ฒด๋ฅผ HTMLCollection์œผ๋กœ ๋ฐ˜ํ™˜ํ•จ
console.log(document.getElementsByClassName("btn")); //btn class ์ „์ฒด๋ฅผ HTML Collection์œผ๋กœ ๋ฐ˜ํ™˜ํ•จ
  • getElementsByTagName & getElementsByClassName โ†’ HTML Collection์„ ๋ฐ˜ํ™˜, ๋…ธ๋“œ์™€ ๋‹ค๋ฅด๊ฒŒ DOM์ด ๋ณ€ํ•˜๋ฉด ์ž๋™์œผ๋กœ ์—…๋ฐ์ดํŠธ ๋œ๋‹ค.

2. ๐ŸฅณCreating and inserting elements

์š”์†Œ ์ƒ์„ฑ/์‚ฝ์ž…ํ•˜๊ธฐ

insertAdjacentHTML & innerHTML

  • insertAdjacentHTML : when you want to add to existing HTML in an element, adding position determined by the position parameter.
  • innerHTML : when you want to start from scratch with your own HTML, will completely replace all the HTML inside of the element.
const messagebanner = document.createElement("div"); //div ๋ผ๋Š” element๋ฅผ ์ƒˆ๋กœ ๋งŒ๋“ฆ
messagebanner.classList.add("cookie--msg"); //cookie--msg class๋ฅผ ์ถ”๊ฐ€
// message.textContent = "We use cookie for improved functionality";

messagebanner.innerHTML =
  'We use cookie for improved functionality <button class="btn btn--close--cookie">Got it!</button>'; //innerHTML๋กœ div ์•ˆ์— HTML๋‚ด์šฉ์„ ์‚ฝ์ž…ํ•จ

//header.prepend(messagebanner); // add to first child
header.append(messagebanner); // add to last child
//header.append(messagebanner.cloneNode(ture)); // copy node
//header.before(messagebanner); // add in front of header
//header.after(messagebanner);  // add at the back of header

3. ๐Ÿ˜ฃDeleting elements

์š”์†Œ ์‚ญ์ œํ•˜๊ธฐ

document
  .querySelector(".btn--close--cookie")
  .addEventListener("click", function () {
    messagebanner.remove();
  });
profile
Persistence pays off.

0๊ฐœ์˜ ๋Œ“๊ธ€