简体   繁体   中英

How to get a sibling element by class name upon button click?

I have a table with similar rows and I am trying to get the value "Star" when the button is clicked.

<tr>
    <td class="shape">Star</td>
    <td class="weight">3</td>
    <td><button>Click</button></td>
</tr>

Code I have tried:

<script>
    const delButton = event.target;
    var prevShape = delButton.getElementsByClass("shape").previousSibling.innerHtml;  
</script>

Delegate:

 window.addEventListener("load", function() { // on page load document.getElementById("tb").addEventListener("click", function(e) { const tgt = e.target; if (tgt.tagName === "BUTTON") { const shape = tgt.closest("tr").querySelector(".shape").textContent; console.log(shape); } }) })
 <table> <tbody id="tb"> <tr> <td class="shape">Circle</td> <td class="weight">3</td> <td><button>Click</button></td> </tr> <tr> <td class="shape">Star</td> <td class="weight">3</td> <td><button>Click</button></td> </tr> </tbody> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM