Skyrpon Skyrpon - 1 year ago 79
Javascript Question

How do I select the ID of a parentNode from an Input with DOM?

When I click on the Input it should give me the ID of the div, but instead that give me an error in console "Cannot read property 'id' of undefined".



function add(){
console.log(this.parentNode.id);
}

<div id="example">
<img src="" alt="" />
<input type="button" value="click me" onclick="add()">
<h3>Title</h3>
<p>Price</p>
<p>Description</p>
</div>




Answer Source

Define a parameter at add function and pass this to the function call. Without using .onclick or .addEventListener() attached to the element this is the global object window within the function call at event attribute handler at JavaScript at browser

function add(el) {
  console.log(el.parentNode.id);
}
<div id="example">
  <img src="" alt="" />
  <input type="button" value="click me" onclick="add(this)">
  <h3>Title</h3>
  <p>Price</p>
  <p>Description</p>
</div>

Alternatively, using .addEventListener()

function add(event) {
  console.log(this.parentNode.id);
}

onload = function() {
  document.querySelector("#example input[value='click me']")
  .addEventListener("click", add)
}
<div id="example">
  <img src="" alt="" />
  <input type="button" value="click me">
  <h3>Title</h3>
  <p>Price</p>
  <p>Description</p>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download