상세 컨텐츠

본문 제목

[TestDome] HTML/CSS and JavaScript: Image Gallery (ECMAScript 7)

PROGRAMMING/Web

by koharin 2021. 1. 31. 03:40

본문

728x90
반응형

문제


 

 

제출코드


function setup() {
    var ele = document.getElementsByClassName("remove");
    for (var i = 0; i < ele.length; i++) {
        ele[i].addEventListener('click', function () {
            this.parentNode.remove();
        });
    }
}

// Example case. 
document.body.innerHTML = `
<div class="image">
<img src="https://goo.gl/kjzfbE" alt="First">
<button class="remove">X</button>
</div>
<div class="image">
<img src="https://goo.gl/d2JncW" alt="Second">
<button class="remove">X</button>
</div>`;

setup();

document.getElementsByClassName("remove")[0].click(); // remove 첫번째 div element
console.log(document.body.innerHTML);

 

 

문제풀이 과정


<!DOCTYPE html>
<html>
    <head>
        <title>TestDome HTML/CSS and JavaScript Test</title>
    </head>
    <body>
        <div class="image">
            <img src="https://goo.gl/kjzfbE" alt="First">
            <button class="remove">X</button>
        </div>
        <div class="image">
            <img src="https://goo.gl/d2JncW" alt="Second">
            <button class="remove">X</button>
        </div>
        <script src="testdome2.js"></script>
    </body>
</html>
function setup() {
    var els = document.getElementsByClassName("remove");
    console.log(els);
    for (var i = 0; i < els.length; i++) {
        els[i].addEventListener('click', function () {
            this.parentNode.remove(); //e.target.closest('div.image').remove();
        });
    }
}

// Example case. 
document.body.innerHTML = `
<div class="image">
<img src="https://goo.gl/kjzfbE" alt="First">
<button class="remove">X</button>
</div>
<div class="image">
<img src="https://goo.gl/d2JncW" alt="Second">
<button class="remove">X</button>
</div>`;

setup();

//document.getElementsByClassName("remove")[0].click();
console.log(document.body.innerHTML);

 

 

 

 

remove 클래스의 버튼이 클릭됐을 때 <div> parent 내 element들를 제거하는 방법


ele[i].addEventListener('click', function () {
	this.parentNode.remove(); 
});

ele[i].addEventListener('click', function (e) {
	e.target.closest('div.image').remove();
});

ele[i].addEventListener('click', function (e) {
	e.currentTarget.closest('div.image').remove();
});

ele[i].addEventListener('click', function (e) {
	e.currentTarget.parentNode.remove();
});

ele[i].addEventListener('click', function (e) {
	e.target.parentNode.remove();
});
728x90
반응형

관련글 더보기