Front-End/JavaScript

[JavaScript_error] 01. HTMLCollection๋Š” forEach, filter ๋“ฑ์„ ์‚ฌ์šฉ ๋ถˆ๊ฐ€.

Bigone17 2022. 1. 8. 16:37

๐ŸŸก HTMLCollection๋Š” forEach, filter ๋“ฑ์„ ์‚ฌ์šฉ ๋ถˆ๊ฐ€.

 - JS๋กœ HTML ์š”์†Œ๋ฅผ ๋ถˆ๋Ÿฌ์˜ค๊ณ  ์‹ถ์„ ๋•Œ document.getElementsBy~~ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๊ฐ€์ ธ์˜ฌ ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์ด๋•Œ ๊ฐ€์ ธ์˜จ element๋“ค์€ HTMLCollection๊ฐ์ฒด ํ˜•ํƒœ๋กœ ๊ฐ€์ ธ์˜ค๋Š”๋ฐ, ๋ฐฐ์—ด์— ๋‹ด๊ฒจ ์˜ค๊ธธ๋ž˜ ๋‹น์—ฐํžˆ map, filter, forEach๊ฐ€ ๋˜๋Š” ์ค„ ์•Œ์•˜์œผ๋‚˜ ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

let checkboxList = document.getElementsByClassName('allDelete');

๊ฐ€์ ธ์˜จ element๋“ค

 

 

  Array HTMLCollection
ํ˜•ํƒœ
filter ํ•จ์ˆ˜
forEach ํ•จ์ˆ˜

 

 - ์œ„ ํ‘œ์—์„œ ๋ณด์‹œ๋Š” ๊ฒƒ์ฒ˜๋Ÿผ HTMLCollection์€ filter, forEach ๋“ฑ Array์—์„œ ๊ธฐ๋ณธ์ ์œผ๋กœ ์ œ๊ณตํ•ด์ฃผ๋Š” ํ•จ์ˆ˜๋ฅผ ์ œ๊ณตํ•˜์ง€ ์•Š๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ HTMLCollection์˜ ์š”์†Œ๋“ค์„ ์ˆœํšŒํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์—ฌ๋Ÿฌ ๊ฐ€์ง€๊ฐ€ ์žˆ์ง€๋งŒ 3๊ฐ€์ง€ ๋ฐฉ๋ฒ•์„ ์†Œ๊ฐœํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

 

๐ŸŸฃ 1. for๋ฌธ์œผ๋กœ ์š”์†Œ ์ˆœํšŒํ•˜๊ธฐ

for(let i=0; i<checkboxList.length; i++){
    console.log(checkboxList[i].className);
}

 

๐ŸŸฃ 2. Array.prototype์— ๋ฐ”์ธ๋”ฉํ•˜๊ธฐ

Array.prototype.forEach.call(checkboxList,(element) => {
    console.log(element.className);
})

 

๐ŸŸฃ 3. HTMLCollection.prototype์— ํ•จ์ˆ˜ ์ง์ ‘ ์ƒ์„ฑ

HTMLCollection.prototype.forEach = Array.prototype.forEach;

checkboxList.forEach((element) =>{
    console.log(element.className);
})

 

 

๐ŸŽˆ Array ๊ฐ™์ด ์ƒ๊ฒผ๋‹ค๊ณ  ๋‹ค ๊ฐ™์€ Array๊ฐ€ ์•„๋‹ˆ์—ˆ๋‹ค๋Š” ๊ฑธ ๋‹ค์‹œ ํ•œ๋ฒˆ ์•Œ๊ฒŒ ๋๋‹ค....

728x90
๋ฐ˜์‘ํ˜•