Solution 1 :

main[0].removeChild(main[0].childNodes[0]); // What should I write instead of CHILDNODES[0]

main[0].removeChild(this) // this refers to the clicked element


As the indices suggest, main[0].removeChild(main[0].childNodes[0]); removes the first element (with index 0).

If the element is clicked, it is this inside the onclick function, so you have direct reference to it. A more general approach would be:

div1.onclick = function () {

or (if you don’t mind it does not work in Internet Explorer) you can directly remove the this element, which is even more elegant and readable:

div1.onclick = function () {

Solution 2 :

You could add the event listener then reference the event target like this:

   for (var x = 0; x < document.getElementsByTagName('div').length; x++) { 
     document.getElementsByTagName('div')[x].addEventListener('click', event => { 
       console.log(, ' was clicked') 

Solution 3 :

div1.onclick = function (e) {

Problem :

I want to remove exactly the div onclick, not in sequence. I’ve tried so many ways to fix it, but unfortunately it didn’t work.I don’t know what to do. So when I click on the div, it removes the div in sequence, but I need to remove exacty the div that Ii was clicking.

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
        body {
            display: flex;
            flex-direction: column;
            color: white;
        div:hover {
            cursor: pointer;



    <div class="main"></div>
    <div class="result"></div>

        var letters = ['O', 'T', 'V', 'I', 'M', 'N', 'I', 'O', 'A', 'T']

var main = document.getElementsByClassName('main')
var result = document.getElementsByClassName('result')
main[0].style.display = 'flex'
result[0].style.display = 'flex'
function rand_color() {
    var color = '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6)
    return color;

for (i = 0; i < letters.length; i++) {

    var div1 = document.createElement('div') = "30px" = "60px" = "70px" = rand_color(); = "80px" = "center"
    div1.innerText = letters[i]
    div1.onclick = function () {
        main[0].removeChild(main[0].childNodes[0]); `What should I write instead of CHILDNODES[0]`
        var div2 = document.createElement('div')
        div2.innerHTML = this.innerText = "30px" = "60px" = "70px" = rand_color() = "80px" = "center"
        div2.ondblclick = function () {





Comment posted by Unmitigated

Please elaborate on what the issue is.

Comment posted by Inesa Adamyan

Can you try my code please? When you clicking on the div it will be removed, but that doesn’t work.

Comment posted by Poul Bak

While this might answer the question, a short explanation will approve the answer.

Comment posted by deadshot

add some explanation how your answer solves the OP’s problem

Comment posted by iguypouf

Actually, if you took the time to read the question, its basically “