Reputation: 83
I am trying to select the parent element of a clicked button, and find the child elements text of that parent element however it is returning undefined
.
var add = document.getElementById("add").parentElement.nodeName;
I found how we can access the parent element's node name, but I can't select it's child element by id
.
Currently I am trying to get attributes for selected elements and user alert()
to display them, however it's not working as expected. The code below is what I currently have:
window.onload = function(){
add();
}
function add() {
var add = document.querySelector(".add").parentNode;
var id = document.querySelector(".id").innerHTML;
var name = document.querySelector(".std").innerHTML;
alert(id);
alert(name);
}
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<th>S.N.</th><th>Name</th><th>Action</th>
</tr>
<tr>
<td class='id'>1</td><td class='std'>Riya</td><td id='del'>DEL</td>
</tr>
<tr>
<td class='id'>2</td><td class='std'>Sonam</td><td class='add'>ADD</td>
</tr>
</table>
</body>
</html>
Upvotes: 1
Views: 3538
Reputation: 46
id
attribute value must be unique across your HTML. So if you want to have multiple elements with the same identifier use class
, also you need to know the index of the element you are targeting.
visit this link for more info about id attribute
You have a typo, the correct attribute is innerHTML
not innerHtml and as mentioned before you need to know the index of the element
window.onload = function(){
add();
}
function add() {
var add = document.getElementById("add").parentNode;
var id = document.querySelectorAll("#id")[0].innerHTML;
var name = document.querySelectorAll("#std")[0].innerHTML;
alert(id);
alert(name);
}
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<th>S.N.</th><th>Name</th><th>Action</th>
</tr>
<tr>
<td id='sn'>1</td><td id='name'>Riya</td><td id='del'>DEL</td>
</tr>
<tr>
<td id='id'>2</td><td id='std'>Sonam</td><td id='add'>ADD</td>
</tr>
</table>
</body>
</html>
Upvotes: 0
Reputation: 30360
There are two issues here:
document.querySelector()
when selecting a single element, rather than document.querySelectorAll()
which is used to select multiple elementsinnerHTML
field should be used instead of innerHtml
Note that document.querySelector()
returns the first selected element (if any), where as document.querySelectorAll()
returns a NodeList
containing selected elements.
Here's a working snippet:
window.onload = function(){
add();
}
function add() {
var add = document.getElementById("add").parentNode;
/* Use querySelector for single element, and use innerHTML */
var id = document.querySelector("#id").innerHTML;
var name = document.querySelector("#std").innerHTML;
alert(id);
alert(name);
}
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<th>S.N.</th><th>Name</th><th>Action</th>
</tr>
<tr>
<td id='sn'>1</td><td id='name'>Riya</td><td id='del'>DEL</td>
</tr>
<tr>
<td id='id'>2</td><td id='std'>Sonam</td><td id='add'>ADD</td>
</tr>
</table>
</body>
</html>
Hope that helps
Upvotes: 2