쿼리 실행 방법선택기All and getElementsBy* 메서드가 반환됩니까?
행 getElementsByClassName
(그리고 비슷한 기능은 다음과 같습니다.getElementsByTagName
그리고.querySelectorAll
을 와 동일하게 작업합니다.getElementById
아니면 그들은 요소들의 배열을 반환합니까?
제가 질문하는 이유는 모든 요소의 스타일을 바꾸려고 하기 때문입니다.getElementsByClassName
.. 아래 참조.
//doesn't work
document.getElementsByClassName('myElement').style.size = '100px';
//works
document.getElementById('myIdElement').style.size = '100px';
ID가 고유해야 하므로 코드가 작동하므로 함수는 항상 정확히 하나의 요소를 반환합니다(또는null
발견되지 않은 경우).
그러나 메서드 , , 및 메서드는 반복 가능한 요소 모음을 반환합니다.
메서드 이름은 다음과 같은 힌트를 제공합니다.getElement
단수를 암시하는 반면에getElements
복수의 뜻을 내포하고 있습니다.
메서드는 단일 요소도 반환하고 반복 가능한 컬렉션도 반환합니다.
반복 가능 집합은 a 또는 a일 수 있습니다.
getElementsByName
그리고 둘 다 a를 반환하도록 지정됩니다.NodeList
; 다른 방법은 다음을 반환하도록 지정됩니다.HTMLCollection
일부 를 다르게 에서는 를 하고 하고 를 .
모두 Elements한 속성을 과 한 을 하지 한 하지 을 한 과 style
document.getElements
…(
…)
a합니다.즉, a.NodeList
은HTMLCollection
가가 style
하나의; Element
가 있습니다.style
.
이러한 "array-like" 컬렉션은 0개 이상의 요소를 포함하는 목록으로, 요소에 액세스하기 위해 이를 반복해야 합니다.배열과 유사하게 반복할 수 있지만 s와 다릅니다.
현대의 브라우저에서는 다음과 같은 표제어를 적절한 배열로 변환할 수 있습니다. 그런 다음 다음을 사용할 수 있습니다.forEach
기타 배열 방법(예: 반복 방법):
Array.from(document.getElementsByClassName("myElement"))
.forEach((element) => element.style.size = "100px");
에서 에서 을 지원하지 않는 이전 브라우저에서Array.from
또는 반복 방법을 사용할 수 있습니다.그런 다음 실제 배열을 사용하는 것처럼 반복할 수 있습니다.
var elements = Array.prototype.slice
.call(document.getElementsByClassName("myElement"));
for(var i = 0; i < elements.length; ++i){
elements[i].style.size = "100px";
}
당신은 또한 다음과 같이 반복할 수 있습니다.NodeList
아니면HTMLCollection
그 자체이지만 대부분의 상황에서 이러한 컬렉션은 라이브(MDN 문서, DOM 사양), 즉 DOM이 변경됨에 따라 업데이트됩니다.따라서 루프를 할 때 요소를 삽입하거나 제거하는 경우 실수로 일부 요소를 건너뛰거나 무한 루프를 만들지 않도록 해야 합니다.MDN 문서는 방법이 실시간 수집을 반환하는지 정적 수집을 반환하는지 항상 기록해야 합니다.
를 들어, 를 , a.NodeList
과은몇지복을다복을shn 등의 몇 가지 방법을 합니다.forEach
최신 브라우저의 경우:
document.querySelectorAll(".myElement")
.forEach((element) => element.style.size = "100px");
for
루프를 사용할 수도 있습니다.
var elements = document.getElementsByClassName("myElement");
for(var i = 0; i < elements.length; ++i){
elements[i].style.size = "100px";
}
부제: 생활량이 생활량이 됩니다. NodeList
생업을 이루게 됩니다. HTMLCollection
이 두 즉, 도 스럽게 스럽게 도 .
jQuery와 같은 라이브러리는 DOM 쿼리를 조금 더 짧게 만들고 "하나의 요소"와 "요소 모음" 위에 추상화 계층을 생성합니다.
$(".myElement").css("size", "100px");
하고 가 과 가 의 차이인 배열을 개체로 사용하고 있습니다.getElementbyId
그리고.getElementsByClassName
다음과 같습니다.
getElementbyId
ID가 있는 요소가 없으면 Element 개체 또는 null을 반환합니다.getElementsByClassName
일치하는 요소를 찾을 수 없는 경우 길이가 0인 실시간 HTML 컬렉션을 반환합니다.
getElementsByClassName
getElementsByClassName(classNames)
method는 클래스를 나타내는 고유한 공백 구분 토큰의 순서가 없는 집합을 포함하는 문자열을 사용합니다.는 라이브가를야다다an을 반환해야 .NodeList
공백에서 문자열을 분할하여 클래스를 얻은, 해당 인수에 지정된 모든 클래스를 가진 문서의 모든 요소를 포함하는 개체입니다.인수에 지정된 토큰이 없는 경우 메서드는 빈 NodeList를 반환해야 합니다.
https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#getelementsbyclassname
요소별 가져오기이드
getElementById() 메서드는 지정한 ID로 첫 번째 요소에 액세스합니다.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
코드에 있는 행:
1 - document.getElementsByClassName('myElement').style.size = '100px';
예상대로 작동하지 않을 것입니다. 왜냐하면getElementByClassName
배열을 반환하고 배열은 다음을 가질 수 없습니다.style
property,은 각은,할수다각h에 접근할 수 .element
그것들을 반복함으로써.
이 이 기능이getElementById
사용자를 위해 작동했습니다. 이 함수는 직접 개체를 반환합니다.따라서 당신은 다음에 접속할 수 있을 것입니다.style
소유물.
ES6는 배열과 유사하거나 반복 가능한 개체로부터 새 배열 인스턴스를 생성하는 메소드를 제공합니다.
let boxes = document.getElementsByClassName('box');
setTimeout(() => {
Array.from(boxes).forEach(v => v.style.background = 'green');
console.log(Array.from(boxes));
}, 500);
.box {
width: 50px;
height: 50px;
margin: 5px;
background: blue;
display: inline-block;
}
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
코드 조각 안에서 볼 수 있듯이 함수를 사용한 후 각 요소를 조작할 수 있습니다.
The same solution using **`jQuery`**.
$('.box').css({'background':'green'});
.box {
width: 50px;
height: 50px;
margin: 5px;
background: blue;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
getElementsByClassName() 메서드는 지정된 클래스 이름을 가진 문서의 모든 요소 모음을 NodeList 개체로 반환합니다.
NodeList 개체는 노드 모음을 나타냅니다.노드는 인덱스 번호로 액세스할 수 있습니다.지수는 0에서 시작합니다.
팁: NodeList 개체의 길이 속성을 사용하여 지정된 클래스 이름을 가진 요소의 수를 결정한 다음 모든 요소를 순환시켜 원하는 정보를 추출할 수 있습니다.
δ, getElementsByClassName
클래스 이름을 사용할 수 있습니다.
HTML 본문인 경우:
<div id="first" class="menuItem"></div>
<div id="second" class="menuItem"></div>
<div id="third" class="menuItem"></div>
<div id="footer"></div>
그리고나서var menuItems = document.getElementsByClassName('menuItem')
는 (의 상위 의3닌을다을다위d닌na)tnet(의) .<div>
이름과 에 된 과 하기 입니다 입니다 하기 과 된
다음를 반복할 수 ( 를 할 할 ).<div>
이):s 을 한 을 한 :
for (var menuItemIndex = 0 ; menuItemIndex < menuItems.length ; menuItemIndex ++) {
var currentMenuItem = menuItems[menuItemIndex];
// do stuff with currentMenuItem as a node.
}
요소와 노드 간의 차이점에 대한 자세한 내용은 이 게시물을 참조하시기 바랍니다.
다른 말로
document.querySelector()
지정한 셀렉터의 처음 한 요소만 선택합니다.배열을 뱉어내는 것이 아니라 하나의 값입니다.와 유사합니다.document.getElementById()
ID는 고유해야 하므로 ID 요소만 가져옵니다.document.querySelectorAll()
지정된 셀렉터가 있는 모든 요소를 선택하고 배열로 반환합니다.와 유사합니다.document.getElementsByClassName()
과 ㅇㅇㅇ을 .document.getElementsByTagName()
태그만.
querySelector를 사용하는 이유는 무엇입니까?
그것은 단지 쉽고 간결하게 하기 위한 목적으로만 사용됩니다.
getElement/sBy를 사용하는 이유*
더 빠른 성능.
왜 이런 성능 차이가 나죠?
두 가지 선택 방법 모두 NodeList를 만들어 추가로 사용할 목적이 있습니다.querySelectors는 Selectors와 함께 정적 노드 목록을 생성하므로 처음부터 새로 만들어야 합니다.
getElement/sBy*는 현재 DOM의 기존 라이브 NodeList를 즉시 적용합니다.
따라서 언제 어떤 방법을 사용할지는 본인/프로젝트/기기에 달려 있습니다.
인포스
실행하면 단일 요소를 얻을 수 있습니다.
document.querySelector('.myElement').style.size = '100px';
클래스 .myElement의 첫 번째 요소에 적용될 예정입니다.
만약 당신이 이것을 당신에게 추천하는 클래스의 모든 요소에 적용하기를 원한다면 나는 당신에게 사용하기를 제안합니다.
document.querySelectorAll('.myElement').forEach(function(element) {
element.style.size = '100px';
});
배열 유사 목록을 반환합니다.
배열을 예제로 만듭니다.
var el = getElementsByClassName("elem");
el = Array.prototype.slice.call(el); //this line
el[0].appendChild(otherElem);
/*
* To hide all elements with the same class,
* use looping to reach each element with that class.
* In this case, looping is done recursively
*/
const hideAll = (className, i=0) => {
if(!document.getElementsByClassName(className)[i]){ //exits the loop when element of that id does not exist
return;
}
document.getElementsByClassName(className)[i].style.visibility = 'hidden'; //hide element
return hideAll(className, i+1) //loop for the next element
}
hideAll('appBanner') //the function call requires the class name
ES5하는 모든 으로 IE8 이상의 를 사용하면 ES5+의 "E8"을 사용할 수 .Array.prototype.forEach
방법.
Array.prototype.forEach.call(document.getElementsByClassName('answer'), function(el) {
el.style.color= 'red';
});
그래서 저는 이것이 제 질문에서 중복된 것이고 제 질문을 삭제해야 한다고 들었습니다. 포럼을 깨끗하게 유지하고 질문할 권리를 유지하기 위해 그렇게 할 것입니다.
제 질문과 이 질문은 정말 다르다고 생각하기 때문에 저는 제 질문에 대한 답을 지적할 것이므로 이 페이지에서 지식을 완성하고 정보가 손실되지 않을 것입니다.
질문.
나는 스니펫에 다음과 같은 코드를 가지고 있습니다.
document.getElementsByClassName("close")[0]
, 뭐, 뭐, 뭐...[0]
하고 있습니까?대괄호가 사용되는 것을 본 적이 없습니다.
getElementsByClassName
어떤 용도로 사용됩니까?그리고 jQuery로 변환하려면 어떻게 해야 합니까?
정답.
에는 의 는 과 가 있습니다.
[0]
실제로 배열로 사용되고 있으며 0이므로 지정된 클래스가 처음 사용되는 것을 의미합니다.위와 같은 것.
나는 정말로 할 수 없었고 아무도 대답하지 않았습니다.이는서서tef 코드 중
event. target
사용할 수 없습니다.$("#myModal")
에 대신에document.getElementById("myModal")
해야 한다고 하지만, 이 형태는 효과를 는 해야 하지만 는 을 하는 입니다 jQuery 를 이 입니다 는 를 는 이
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
body {font-family: Arial, Helvetica, sans-serif;}
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<h2>Modal </h2>
<button id="myBtn">Open Modal</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
갱신하다
제 질문을 삭제할 수도 없고 사람들이 만족하지 못하는 것 같아요, 어떻게 해야 할지 정말 모르겠어요.
Super Old School 솔루션:
[].forEach.call(document.getElementsByClassName('myClass'), function (el) {
el.style.size = '100px';
});
드렌지의 구체적인 사건에 대한 답은...
다음과 같이 모든 요소에 대해 작동하는 함수를 만들 수 있으며 변환할 요소의 개수를 전달할 수 있습니다.
// Binds `wordButtons` to an (array-like) HTMLCollection of buttons
const wordButtons = document.getElementsByClassName("word");
// Applies the `slantWord` function to the first word button
slantWord(1);
// Defines the `slantWord` function
function slantWord(wordNumber) {
const index = wordNumber - 1; // Collection index is zero-based
wordButtons[index].style.transform = "rotate(7deg)"; // Transforms the specified button
}
<div class="wordGameContainer">
<button class="word word1">WORD 1</button>
<button class="word word2">WORD 2</button>
<button class="word word3">WORD 3</button>
<button class="word word4">WORD 4</button>
</div>
<div>
<button onclick="moveWord()" class="playButton">PLAY</button>
</div>
언급URL : https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return
'source' 카테고리의 다른 글
MySQL 계산 백분율 (0) | 2023.09.06 |
---|---|
모바일 웹 페이지에서 확대/축소를 "비활성화"하려면 어떻게 해야 합니까? (0) | 2023.09.06 |
수행 표시줄에 뒤로 단추 표시 (0) | 2023.09.06 |
PHP에서 객체 배열을 복제하는 방법은? (0) | 2023.09.06 |
ajax 문제 - firebug에서는 200 OK이지만 응답 본문이 없는 빨간색 (0) | 2023.09.06 |