DOM
47088 ワード
HTMLとは
DOMとは
-HTMLドキュメントとJavaScriptオブジェクトはツリー構造です.
document
オブジェクトを使用してHTMLドキュメントを操作できます.DOM構造の参照
console.dir();
ドキュメントを()に挿入し、objectとして表示します.サブ要素のクエリー
親の照会
document.body.children
document.body.parentElement
DOMによるHTMLの変更
document 객체를 통해서 HTML 엘리먼트를 만들고(CREATE), 조회하고(READ), 갱신하고(UPDATE), 삭제하는(DELETE) 하는 방법을 알아보자.
1.JavaScriptから要素を作成する(createElement)
const tweetDiv = document.createElement('div')
2.appendを使用して属性を追加(要素を追加)
document.body.append(tweetDiv)
.append()
// Inserting a Node object
const parent = document.createElement('div');
const child = document.createElement('p');
parent.append(child);
// This appends the child element to the div element
// The div would then look like this <div><p></p></div>
// Inserting a DOMString
const parent = document.createElement('div');
parent.append('Appending Text');
// The div would then look like this <div>Appending Text</div>
.appendChild()
// Inserting a Node object
const parent = document.createElement('div');
const child = document.createElement('p');
parent.appendChild(child);
// This appends the child element to the div element
// The div would then look like this <div><p></p></div>
// Inserting a DOMString
const parent = document.createElement('div');
parent.appendChild('Appending Text');
// Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'
2-1. append vs appendChild
違いは、ノードオブジェクトが追加できるDOMStirngオブジェクトとノードオブジェクトが追加できるノードオブジェクトしか追加できないことです.
// .append에서 DOMStirng과 Node object 추가 가능하지만 .appendChild는 Node object만 가능
const parent = document.createElement('div');
const child = document.createElement('p');
// Appending Node Objects
parent.append(child) // Works fine
parent.appendChild(child) // Works fine
// Appending DOMStrings
parent.append('Hello world') // Works fine
parent.appendChild('Hello world') // Throws error
//.append()는 여러 요소 추가 가능하지만 .appendChild()는 하나의 Node object만 가능
const parent = document.createElement('div');
const child = document.createElement('p');
const childTwo = document.createElement('p');
parent.append(child, childTwo, 'Hello world'); // Works fine
parent.appendChild(child, childTwo, 'Hello world');
// Works fine, but adds the first element and ignores the rest
// .append()는 반환값이 없고 .appendChild()는 반환값이 Node object이다.
const parent = document.createElement('div');
const child = document.createElement('p');
const appendValue = parent.append(child);
console.log(appendValue) // undefined
const appendChildValue = parent.appendChild(child);
console.log(appendChildValue) // <p><p>
2-2. prepend vs append
prepend : One or more nodes to insert before the first child node currently in the ParentNode.
Advance
<div class="a">
<span></span>
</div>
<div class="b"></div>
const span = document.querySelector(‘span’);
const divB = document.querySelector(‘.b’);
divB.appendChild(span);
リファレンスリンク 3.JavaScriptでDOMを使用して要素を読み込む(querySelector)
<div>HTML Document</div>
<div id = 'div'>HTML Document</div>
<div id = 'div2'>
<span class = 'span'>HTML Document</span>
</div>
document.querySelector('div');
//결과 : div
document.querySelector('#div');
//결과 : <div id = 'div'>HTML Document</div>
let div = document.querySelector('#div2');
div.querySelector('.span');
//결과 : <span class = 'span'>HTML Document</span>
4. textContent, classList.追加(要素更新)
const oneDiv = document.createElement('div') // 요소 생성
console.log(oneDiv) // <div></div>
oneDiv.textContent = 'dev'; // 내용 삽입
console.log(oneDiv) // <div>dev</div>
oneDiv.classList.add('tweet') // class 속성 추가
console.log(oneDiv) // <div class="tweet">dev</div>
const container = document.querySelector('#container') // 부모 엘리먼트
container.append(oneDiv) //append로 요소 추가
4-1. element.classList
<html>
<head>
<title>
안녕~
</title>
</head>
<body>
<div class='divTest'>
<!-- 내용 시작 -->
<p class='pTest'>은하수를 여행하는 히치하이커를 위한 안내서</p>
<p class='pTest'>오리엔트 특급살인</p>
</div>
</body>
</html>
document.querySelector('div').classList
//결과 : DOMTokenList ["divTest", value: "divTest"]
let div = document.querySelector('div').classList
//결과 : <div class="divTest"> ... </div>
div.classList.remove('divTest');
//결과 : <div class> ... </div>
div.classList.add('anotherclass')
// 결과 : <div class='anotherclass'> ... </div>
2つの引数の場合、2番目の引数がtrueの場合、指定したクラス値が追加され、falseの場合は削除されます.
div.classList.toggle('visible');
//결과 <div class=""anotherclass visible"> ... </div>
div.classList.toggle('visible', false);
//결과 <div class="anotherclass"> ... </div>
div.classList.toggle('visible', true);
//결과 <div class="anotherclass visible"> ... </div>
div.classList.contains('new')
//결과 false
//replace 후는 true
div.classList.replace('anotherclass','new');
// 결과 <div class="new"> ... </div>
4-2. setAttribute()は、属性を追加することによってidやclassなどを生成することができる。
oneDiv.setAttribute("id","test"); //id="test" 속성을 추가
4-3. textContent vs innerHTML
innerHTML:ラベルとコンテンツをすべてインポートします.ラベルを付けることができます.
<p id = 'p'><h1 style="color:blue">innerHTML</h1></p>
let p = document.querySelector('#p');
p.innerHTML // <h1 style="color:blue">innerHTML</h1>
textContent:スペースとコンテンツをすべてインポートします.価格は再配分できます.<p id="p"><h1 >textContent</h1></p>
// textContent
注:リンク1 メモリンク2
5.HasChildNodes()メソッド
아래 예시에서는 "foo"라는 id를 가진 요소를 찾고 "foo" 요소에게 자식노드가 있으면 첫번째 자식노드를 제거해줍니다.
let foo = document.getElementById("foo");
if ( foo.hasChildNodes() ) {
foo.removeChild( foo.childNodes[0] );
}
6. element.childNodes
<div>
<!-- 내용 시작 -->
<p>은하수를 여행하는 히치하이커를 위한 안내서</p>
<p>오리엔트 특급살인</p>
</div>
document.querySelector("div").childNodes
// 결과 NodeList(7) [text,comment, text, p, text, p, text]
div起動後、0番目の配列要素としてtextコンテンツ開始をコメント
コンテンツの開始後、
pはp銀河旅行のヒッチハイクガイド
次のテキストは
pはp東方特級殺人
次のテキストは
結局、ChildNodes
<!-- 내용 시작 -->
<p>은하수를 여행하는 히치하이커를 위한 안내서</p>
<p>오리엔트 특급살인</p>
はい.7. ParentNode.children
<div>
<!-- 내용 시작 -->
<p>은하수를 여행하는 히치하이커를 위한 안내서</p>
<p>오리엔트 특급살인</p>
</div>
document.querySelector("div").children
// 결과 HTMLCollection(2) [p, p]
7-1. children vs childNodes
8.要素の削除(remove,removeChild)
追加
const body = document.querySelector('body')
const div = document.createElement('div')
body.append(div)
div.remove()
const body = document.querySelector('body')
body.innerHTML='' // 자식 엘리먼트 전부 삭제
const body = document.querySelector('body');
while (body.firstChild) {
body.removeChild(container.firstChild);
}
9. node vs element
メモリンク2
参照リンク3
[特定のエンティティを選択してインポート]
ボタンクリック時にDOMを使用して要素を追加
//p 요소를 body에 javascript를 이용해서 추가해 보기
<body>
<p>요소 하나 추가</p>
</body>
let button = document.querySelector('#button'); // 클릭 이벤트할 요소 가져오기
function buttonInput() { // 요소를 추가하는 함수
let p = document.createElement('p');
p.textContent="요소 하나 추가";
let parent = document.querySelector("body");
parent.appendChild(p);*-
}
button.addEventListener('click',buttonInput); //클릭 이벤트 발생 시 이벤트 핸들러 사용
button.onclick = buttonInpu;
エンティティオブジェクト|属性名|属性|
|:---:|:---:|
|tagName|タグ名|
|id|id値|
|classList|classリスト|
|className|class文字列|
|value|form入力値|
|children|サブエイリアス|
|親要素|親要素|
|childNodes|サブノード|
|dataset|属性に含まれる値ですが、実際のデータではありません|
|onclick|イベントをクリック|
バニラエッセンス
Prototypeを使用した作成方法
/* this가 number형인 값을 불러와 함수 작성 가능 */
Number.prototype.[메서드 이름] = function() {
//...함수 실행할 명령어들
}
template tagを使用して表示したい要素のみを表示
<template id='a'>
<span>after</span>
</template>
<div id='b'>before</div>
let b = document.querySelector('#b');
let template = document.querySelector('#a');
let newContent = document.importNode(template.content,true);
// 자식 노드 전부 포함하여 복사
b.textContent = '';
b.appendChild(newContent); //<div id='b'>after</div>
DOMは難しすぎるReference
この問題について(DOM), 我々は、より多くの情報をここで見つけました https://velog.io/@bsy/DOMテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol