[javascript] JavaScript에서 자식 노드와 자식 노드의 차이점은 무엇입니까?

나는 JavaScript를 사용하여 자신을 발견 childNodes했으며 children속성을 가로 질러 뛰어 다녔습니다 . 나는 그들 사이의 차이점이 무엇인지 궁금합니다. 또한 하나는 다른 것보다 선호됩니까?



답변

이것이 Element.children 의 속성 임을 이해하십시오 . 1 Elements 만 있고이 하위 요소는 모두 Element 유형입니다. 2.children

그러나 Node.childNodes 의 속성입니다 . 모든 노드를 포함 할 수 있습니다. .childNodes

구체적인 예는 다음과 같습니다.

let el = document.createElement("div");
el.textContent = "foo";

el.childNodes.length === 1; // Contains a Text node child.
el.children.length === 0;   // No Element children.

.children일반적으로 DOM 조작에서 텍스트 또는 주석 노드 를 반복하지 않기 때문에 사용 하려고합니다 .

텍스트 노드를 조작하려면 .textContent대신 원할 것입니다. 4


1. 기술적으로는 Element에 포함 된 믹스 인 ParentNode 의 속성입니다 .
2. 요소 만 포함 할 수 .children있는 HTMLCollection 이므로 모든 요소입니다.
3. 마찬가지로 NodeList.childNodes 이므로 모든 노드를 보유 할 수 있습니다 .
또는 .innerText. 여기 또는 여기 의 차이점을 참조 하십시오 .


답변

Element.children요소 하위 만 Node.childNodes리턴하고 모두 리턴 노드 자식 . 요소는 노드이므로 요소에서 모두 사용할 수 있습니다.

나는 childNodes더 신뢰할 수 있다고 믿습니다 . 예를 들어, MDC (위에 링크 됨)는 IE children가 IE 9 에서만 가능하다는 점을 지적합니다 childNodes. 브라우저 구현자가 오류를 덜 줄입니다.


답변

지금까지 좋은 대답은 다음을 사용하여 노드 유형을 확인할 수 있다는 것만 추가하고 싶습니다 nodeType.

yourElement.nodeType

이것은 당신에게 정수를 줄 것입니다 : ( 여기 에서 가져온 )

| Value |             Constant             |                          Description                          |  |
|-------|----------------------------------|---------------------------------------------------------------|--|
|    1  | Node.ELEMENT_NODE                | An Element node such as <p> or <div>.                         |  |
|    2  | Node.ATTRIBUTE_NODE              | An Attribute of an Element. The element attributes            |  |
|       |                                  | are no longer implementing the Node interface in              |  |
|       |                                  | DOM4 specification.                                           |  |
|    3  | Node.TEXT_NODE                   | The actual Text of Element or Attr.                           |  |
|    4  | Node.CDATA_SECTION_NODE          | A CDATASection.                                               |  |
|    5  | Node.ENTITY_REFERENCE_NODE       | An XML Entity Reference node. Removed in DOM4 specification.  |  |
|    6  | Node.ENTITY_NODE                 | An XML <!ENTITY ...> node. Removed in DOM4 specification.     |  |
|    7  | Node.PROCESSING_INSTRUCTION_NODE | A ProcessingInstruction of an XML document                    |  |
|       |                                  | such as <?xml-stylesheet ... ?> declaration.                  |  |
|    8  | Node.COMMENT_NODE                | A Comment node.                                               |  |
|    9  | Node.DOCUMENT_NODE               | A Document node.                                              |  |
|   10  | Node.DOCUMENT_TYPE_NODE          | A DocumentType node e.g. <!DOCTYPE html> for HTML5 documents. |  |
|   11  | Node.DOCUMENT_FRAGMENT_NODE      | A DocumentFragment node.                                      |  |
|   12  | Node.NOTATION_NODE               | An XML <!NOTATION ...> node. Removed in DOM4 specification.   |  |

Mozilla 에 따르면 :

다음 상수는 더 이상 사용되지 않으며 더 이상 사용해서는 안됩니다. Node.ATTRIBUTE_NODE, Node.ENTITY_REFERENCE_NODE, Node.ENTITY_NODE, Node.NOTATION_NODE


답변

당신이 찾고있는 방법에 따라 하나를 선택하십시오!?

ParentNode.children 과 함께 갈 것입니다 .

그것은 namedItem모든 어린이를 반복하거나 사용하지 않는 등 어린이 요소 중 하나를 직접 얻을 수있는 방법을 제공 합니다 getElementById.

예 :

ParentNode.children.namedItem('ChildElement-ID'); // JS
ref.current.children.namedItem('ChildElement-ID'); // React
this.$refs.ref.children.namedItem('ChildElement-ID'); // Vue

Node.childNodes 와 함께 갈 것입니다 .

예를 들어 forEach작업 할 때 방법 을 제공하므로window.IntersectionObserver

nodeList.forEach((node) => { observer.observe(node) })
// IE11 does not support forEach on nodeList, but easy to be polyfilled.

Chrome 83에서

는 XMLNode.childNodes가 제공 entries, forEach, item, keys, lengthvalues

ParentNode.childrenitem, lengthnamedItem


답변