js DOM의 몇 가지 일반적인 방법 소개
요소 노드 가져오기 getElementById getElementsByTagName getElementsByClassName
먼저 테스트용 간단한 웹 페이지를 작성합니다.
/*
test.html
*/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<p id="contentId" style="width:500px; height: 30px;background-color: #ccc">这段的id是contentId。</p>
<p class="contentClass" style="width:500px; height: 30px;background-color: #ccc">这段的class name是contentClass。</p>
</body>
</html>
1.
1. 먼저 변수 var contentId = document.getElementById("contentId");
를 정의합니다.
2. 그런 다음 개체 contentId를 출력하고 ID가 contentId인 요소 개체를 반환합니다(3f078ee2bd51f064ba86783b132a56e5). 아래 그림을 참조하세요.

2. getElementsByTagName
1. 먼저 변수를 정의합니다. var contentTag = document.getElementsByTagName("p")
2. 그런 다음 HTMLCollection [ 39ae2a42268023ea5ca018cf390b60c5, b39175b47eb4f25ca688689d3f990331 ]을 반환하는 contentTag를 출력합니다. 하나는 #으로 시작하여 클래스를 나타냅니다. 이름.
3. 계속해서 contentTag[0] 및 출력9ff743490c3ca7a44329d35a1fc0889d
contentTag[ 1] 출력e78b7671e2819eb1750641e2e081343c

이로부터 우리는 볼 수 있습니다 getElementsByTagName 반환되는 것은 배열입니다!
3. getElementsByClassName
1. var contentClass = document.getElementsByClassName("contentClass");
2. contentClass 출력 HTMLCollection [ b39175b47eb4f25ca688689d3f990331 요소 객체가 하나만 있는 경우에도 배열입니다.
3. contentClass[0] 출력e78b7671e2819eb1750641e2e081343c

또한 일부 정보를 얻기 위해 일반적으로 getAttribute, setAttribute, ChildNodes, nodeType, nodeValue, firstChild 및 lastChild 메소드를 사용합니다.
4. getAttribute 및 setAttribute를 사용하여 각각 속성을 가져오고 설정합니다.

스타일 속성을 변경한 후:

5. 그러면 이것은 childNOdes입니다:

즉, e388a4556c0f65e1904146cc1a846bee94b3e26ee717c64999d7867364b1b4a3 개행 문자 0c6dc11e160d3b678d68754cc175188a가 있으며 브라우저는 하위 노드를 찾을 때 이를 텍스트 노드로 처리합니다. childNodes도 배열을 반환한다는 것을 그림에서 볼 수 있습니다.
39ae2a42268023ea5ca018cf390b60c5라면 어떨까요?

nodeType 값에는 12가지 유형이 있으며 일반적으로 사용되는 세 가지 유형이 있습니다. 1은 요소 노드를 나타내고, 2는 속성 노드를 나타내고, 3은 텍스트 노드를 나타냅니다.
nodeValue는 텍스트 노드의 값을 가져올 수 있을 뿐만 아니라 텍스트 노드의 값을 변경할 수도 있습니다.

이 글의 내용이 모두의 공부나 업무에 조금이나마 도움이 되었으면 좋겠습니다. 중국사이트!
js에서 흔히 사용되는 DOM 메소드에 대한 자세한 설명은 PHP 중국어 홈페이지를 참고해주세요!