Get data from another cell

by Paul Leech

HTML

<table align="center">
    <tr>
        <!--the table heading-->
        <th>id</th>
        <th>type</th>
        <th>Price</th>
        <th>examine</th>
    </tr>
    <tr>
        <td onclick="alert(this.innerText)">0</td>
        <td>Book</td>
        <td>500</td>
        <td><button>examine</button> <!-- onclick, get the id value 0 -->
    </tr>
    <tr>
        <td onclick="alert(this.innerText)">1</td>
        <td>Clothing</td>
        <td>30</td>
        <td><button>examine</button> <!-- onclick, get the id value 1 -->
    </tr>
    <tr>
        <td onclick="alert(this.innerText)">2</td>
        <td>Food</td>
        <td>400</td>
        <td><button>examine</button> <!-- onclick, get the id value 2 -->
    </tr>
    <!--...
    there are 100 rows-->
    <tr>
        <td onclick="alert(this.innerText)">99</td>
        <td>Book</td>
        <td>300</td>
        <td><button>examine</button> <!-- onclick, get the id value 99 -->
    </tr>
</table>

<div id="result"></div>

CSS

#result {
  font-family: sans-serif;
  width: 800px;
  margin:0 auto;
  text-align:center;
}

JavaScript

/*
document.querySelectorAll('button').forEach(b => {
  b.addEventListener('click', () => 
  // alert(b.parentNode.parentNode.firstChild.nextSibling.innerHTML)
  alert(b.parentNode.parentNode.secondChild.nextSibling.innerHTML)
  // b.parentNode.parentNode.firstChild.nextSibling.click()
  );
});
*/
const result = document.getElementById('result');
document.querySelectorAll('td').forEach(b => {
  b.addEventListener('click', () =>
    result.innerHTML = "Show Price: <strong>" + b.parentNode.querySelector('td:nth-of-type(3)').innerHTML+'</strong>'
    );
});

/* document.querySelectorAll('td').forEach(b => {
  b.addEventListener('click', () => 
  alert(b.parentNode.parentNode.firstChild.nextSibling.innerHTML)
  //b.parentNode.parentNode.firstChild.nextSibling.click()
  );
}); */