JS - know the id of the button clicked to use in a function

Asked

Viewed 22 times

0

I created a table with a series of buttons, 100 in all, and each button received an id that is generated automatically. I want to know how to get the id of the button that was clicked, because I intend to change its color. I don’t know how to program in JS, but I have to do a job, what I did was through research.

const cellArray = []
let cellWidth = 10
let cellHeight = 10

function start() {
    createCellsDataStructure()
    renderCells()
}

function createCellsDataStructure() {
    const numberOfCells = cellWidth * cellHeight

    for (let i = 0; i < numberOfCells; i++) {
        cellArray[i] = 0
    }
}

function cellsProgation() {

}

function changeColor(){
    
}

function renderCells() {
    let html = '<table cellpadding=0 cellsapcing=0>'
    for (let row = 0; row < cellHeight; row++) {
        html += '<tr>'
        
        for (let column = 0; column < cellWidth; column++) {
            const cellIndex = column + (cellWidth * row)
            html += '<td class="cell-index">'
            html += `<button id="cell-index-${cellIndex}" onClick="changeColor()"></button>`
            html += '</td>'
        }

        html += '</tr>'
    }
    html += '</table>'

    document.querySelector('#cellBlock').innerHTML = html
}


start()
<html>
<head>
    <title>Fundamento de Sistemas</title>
    <style>
        table {
            border-collapse: collapse;
            border: 1px solid #000;
        }

        td {
            width: 50px;
            height: 50px;
            text-align: center;
            vertical-align: center;
            font-family: monospace;
            font-size: 18px;
            border: 1px solid #000;
            position: relative;
        }

        button {
            font-size: 10px;
            height: inherit;
            width: inherit;
            color: #999;
        }
    </style>

</head>
<body>
    <div id="cellBlock"></div>
    <script src="constructor.js"></script>
</body>
</html>

I want each change its color when it is clicked, the intention is to make a mobile automato, if you can give tips on how to do it will be of great help.

  • Normally I use jquery, give a class to buttons, and use this to change the color of the boot

  • One way is to pass this in function: onClick="changeColor(this)", and in function to do so: changeColor(elemento){ var id = elemento.id; }

  • Thanks for the help!!!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.