Program Tip

HTMLCollection, NodeLists 및 객체 배열의 차이점

programtip 2020. 10. 14. 20:51
반응형

HTMLCollection, NodeLists 및 객체 배열의 차이점


나는 항상 DOM과 관련하여 HTMLCollections, 객체 및 배열을 혼동했습니다. 예를 들어 ...

  1. document.getElementsByTagName("td")의 차이점은 무엇입니까 $("td")?
  2. $("#myTable")$("td")객체 (jQuery를이 객체)입니다. console.log가 그 옆에 DOM 요소의 배열도 표시하는 이유는 무엇이며, 배열이 아니라 객체가 아닌가?
  3. 파악하기 어려운 "NodeLists"는 무엇이며 어떻게 선택합니까?

아래 스크립트에 대한 해석도 제공하십시오.

감사합니다

[123,"abc",321,"cba"]=[123,"abc",321,"cba"]
{123:123,abc:"abc",321:321,cba:"cba"}=Object { 123=123, abc="abc", 321=321, more...}
Node= Node { ELEMENT_NODE=1, ATTRIBUTE_NODE=2, TEXT_NODE=3, more...}
document.links= HTMLCollection[a #, a #]
document.getElementById("myTable")= <table id="myTable">
document.getElementsByClassName("myRow")= HTMLCollection[tr.myRow, tr.myRow]
document.getElementsByTagName("td")= HTMLCollection[td, td, td, td]
$("#myTable")= Object[table#myTable]
$("td")= Object[td, td, td, td]


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> 
        <title>Collections?</title>  
        <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script> 
        <script type="text/javascript">
            $(function(){
                console.log('[123,"abc",321,"cba"]=',[123,"abc",321,"cba"]);
                console.log('{123:123,abc:"abc",321:321,cba:"cba"}=',{123:123,abc:"abc",321:321,cba:"cba"});
                console.log('Node=',Node);
                console.log('document.links=',document.links);
                console.log('document.getElementById("myTable")=',document.getElementById("myTable"));
                console.log('document.getElementsByClassName("myRow")=',document.getElementsByClassName("myRow"))
                console.log('document.getElementsByTagName("td")=',document.getElementsByTagName("td"));
                console.log('$("#myTable")=',$("#myTable"));
                console.log('$("td")=',$("td"));
            });
        </script>
    </head>

    <body>
        <a href="#">Link1</a>
        <a href="#">Link2</a>
        <table id="myTable">
            <tr class="myRow"><td>td11</td><td>td12</td></tr>
            <tr class="myRow"><td>td21</td><td>td22</td></tr>
        </table>
    </body> 
</html>

먼저 NodeList의 차이점을 설명하겠습니다 HTMLCollection.

두 인터페이스 모두 DOM 노드의 모음 입니다. 제공하는 방법과 포함 할 수있는 노드 유형이 다릅니다. A는 동안 NodeList노드 유형을 포함 할 수 있습니다,는 HTMLCollection요소 노드 만 포함되어 있습니다.
HTMLCollectiona NodeList동일한 메서드를 제공 하며 추가로 namedItem.

컬렉션은 여러 노드에 대한 액세스를 제공해야 할 때 항상 사용됩니다. 예를 들어 대부분의 선택기 메서드 (예 getElementsByTagName:)는 여러 노드를 반환하거나 모든 자식 ( element.childNodes)에 대한 참조를 가져옵니다 .

자세한 내용은 DOM4 사양-컬렉션을 참조 하세요.

document.getElementsByTagName("td")의 차이점은 무엇입니까 $("td")?

getElementsByTagNameDOM 인터페이스의 메소드입니다. 태그 이름을 입력으로 받아들이고 반환합니다 HTMLCollection( DOM4 사양 참조 ).

$("td")아마도 jQuery입니다. 유효한 CSS / jQuery 선택기를 받아들이고 jQuery 객체를 반환합니다.

표준 DOM 컬렉션과 jQuery 선택 간의 가장 큰 차이점은 DOM 컬렉션이 일반적으로 라이브라는 것입니다 (모든 메서드가 라이브 컬렉션을 반환하지는 않음). 즉, DOM에 대한 모든 변경 사항이 영향을받는 경우 컬렉션에 반영된다는 것입니다. DOM 트리 보기 와 비슷 하지만 jQuery 선택은 함수가 호출 된 순간의 DOM 트리 스냅 샷입니다.

console.log가 그 옆에 DOM 요소의 배열도 표시하는 이유는 무엇이며, 배열이 아니라 객체가 아닌가?

jQuery 객체는 배열과 유사한 객체입니다. 즉, 숫자 속성과 length속성이 있습니다 (배열은 객체 자체 일뿐입니다). 브라우저는 .NET과 같은 특별한 방식으로 배열 및 배열 유사 객체를 표시하는 경향이 있습니다 [ ... , ... , ... ].

파악하기 어려운 "NodeLists"는 무엇이며 어떻게 선택합니까?

내 대답의 첫 번째 부분을 참조하십시오. s는 선택할 수 없으며 선택NodeList결과 입니다.

내가 아는 한 NodeList프로그래밍 방식으로 s 를 생성하는 방법 (즉, 비어있는 것을 생성하고 나중에 노드를 추가 하는 방법)조차없는 한, 일부 DOM 메소드 / 속성에 의해서만 반환됩니다.


0. an HTMLCollection과 a 의 차이점은 무엇입니까 NodeList?

여기에 몇 가지 정의가 있습니다.

DOM 레벨 1 사양-기타 객체 정의 :

HTMLCollection 인터페이스

HTMLCollection은 노드 목록입니다. 개별 노드는 서수 색인이나 노드의 이름 또는 ID 속성으로 액세스 할 수 있습니다. 참고 : HTML DOM의 컬렉션은 기본 문서가 변경 될 때 자동으로 업데이트됨을 의미하는 라이브로 간주됩니다.

DOM 레벨 3 사양-NodeList

인터페이스 NodeList

NodeList 인터페이스는이 컬렉션이 구현되는 방식을 정의하거나 제한하지 않고 정렬 된 노드 컬렉션의 추상화를 제공합니다. DOM의 NodeList 객체는 라이브입니다.

NodeList의 항목은 0부터 시작하는 정수 인덱스를 통해 액세스 할 수 있습니다.

따라서 둘 다 라이브 데이터를 포함 할 수 있습니다. 즉, 값이 업데이트되면 DOM이 업데이트됩니다. 또한 다른 기능 세트를 포함합니다.

스크립트를 실행하는 경우 콘솔을 검사하면 tableDOM 요소에 a childNodes NodeList[2]children HTMLCollection[1]. 왜 다른가요? 때문에 HTMLCollection요소 노드 만 포함 할 수있는 NodeList는 텍스트 노드가 포함되어 있습니다.

여기에 이미지 설명 입력

1. document.getElementsByTagName("td")의 차이점은 무엇입니까 $("td")?

document.getElementsByTagName("td")반환 DOM 요소의 배열 (a NodeList) $("td")에서의 요소를 갖는다 JQuery와 객체 호출 document.getElementsByTagName("td")속성에 0, 1, 2, 등의 주요 차이점은 jQuery 오브젝트 조금 느린 검색 할 수 있지만 모든 편리한 액세스를 제공한다는 것이다 jQuery 함수.

2. $("#myTable")$("td")개체 ( jQuery개체)입니다. console.log그 옆에 DOM 요소의 배열이 표시되는 이유는 무엇이며 , 배열이 아니라 객체가 아닌가?

그들은 그들의 특성을 가진 개체 0, 1, 2, DOM 요소에 등을 설정합니다. 다음은 작동 원리에 대한 간단한 예입니다.

jsFiddle

    var a = {
        1: "first",
        2: "second"
    }
    alert(a[1]);

3. 이해하기 어려운 "NodeLists"는 무엇이며 어떻게 선택합니까?

코드에서 검색하고 getElementsByClassName있으며 getElementsByTagName둘 다 NodeLists를 반환 합니다.

NodeList


추가 참고 사항

HTMLCollection과 NodeList의 차이점은 무엇입니까?

HTMLCollection는 요소 노드 만 (포함 태그 )하고 있는 NodeList는 모든 포함 노드를 .

네 가지 노드 유형이 있습니다.

  1. 요소 노드
  2. attribute node
  3. text node
  4. comment node

nodeTypes

Whitespace inside elements is considered as text, and text is considered as nodes.

Consider the following:

<ul id="myList">
  <!-- List items -->
  <li>List item 1</li> 
  <li>List item 2</li>
  <li>List item 3</li>
  <li>List item 4</li>
  <li>List item 5</li>
</ul>

Whitespace: <ul id="myList"> <li>List item</li></ul>

No whitespace: <ul id="myList"><li>List item</li></ul>

HTMLCollection과 NodeList의 차이점


$("td") is extended jQuery object and it has jQuery methods, it returns jquery object that contains array of html objects. document.getElementsByTagName("td") is raw js method and returns NodeList. See this article


The NodeList objects are collections of Node's, returned for example by x.childNodes property or document.querySelectorAll() method. In some cases, the NodeList is live, which means that changes in the DOM automatically update the collection! For example, Node.childNodes is live:

var c = parent.childNodes; //assume c.length is 2
parent.appendChild(document.createElement('div'));
//now c.length is 3, despite the `c` variable is assigned before appendChild()!!
//so, do not cache the list's length in a loop.

But in some other cases, the NodeList is static, where any changes in the DOM does not affect the content of the collection. querySelectorAll() returns a static NodeList.

The HTMLCollection is a live and ordered collection of elements (it is automatically updated when the underlying document is changed). It can be result of properties like as children or methods like as document.getElementsByTagName(), and could only have HTMLElement's as their items.

HTMLCollection also exposes its members directly as properties by both name and index:

var f = document.forms; // this is an HTMLCollection
f[0] === f.item(0) === f.myForm //assume first form id is 'myForm'

The HTMLElement is just one type of Nodes:

노드 << HTMLElement 상속

The Node can be several types. Most important ones are as following:

  • element (1): An Element node such as <p> or <div>.
  • attribute (2): An Attribute of an Element. The element attributes are no longer implementing the Node interface in DOM4 specification!
  • text (3): The actual Text of Element or Attribute.
  • comment (8): A comment node.
  • document (9): A document node.

So, a big difference is that HTMLCollection contains only HTMLElements but NodeList also contains the comments, white-space texts (carriage return chars, spaces..), etc. Check it as in following snippet:

function printList(x, title) {
  console.log("\r\nprinting "+title+" (length="+x.length+"):");
  for(var i=0; i<x.length; i++) {
    console.log("  "+i+":"+x[i]);
  }
}

var elems = document.body.children; //HTMLCollection
var nodes = document.body.childNodes; //NodeList

printList(elems, "children [HTMLCollection]");
printList(nodes, "childNodes [NodeList]");
<div>para 1</div><!-- MyComment -->
<div>para 2</div>

HTMLCollection과 NodeList는 모두 항목 반복 하는 데 사용할 수 있는 길이 속성을 포함합니다 . for ... in 또는 for each ... in을 사용하여 NodeLists의 항목을 열거하지 마십시오. 또한 길이 및 항목 속성을 열거하고 스크립트가 요소 개체 만 처리해야한다고 가정하면 오류가 발생하기 때문입니다. 또한 for..in은 특정 순서로 숙소 방문을 보장하지 않습니다.

for (var i = 0; i < myNodeList.length; i++) {
  var item = myNodeList[i];
}

참고 URL : https://stackoverflow.com/questions/15763358/difference-between-htmlcollection-nodelists-and-arrays-of-objects

반응형