Manilva
Manilva

Reputation: 13

Output Element ID to Console

I'd like to output the ID of an element when clicked to the browser console, however I can't work out how to do so in string format - currently the output is blank.

The HTML:

<div id = "1" class = "column">
    <a href="javascript:;" onclick="addClassToImage(this)"> <img class="img-class" src="https://manilva.club/wp-content/uploads/2019/04/By-Product.png" alt="By Product" /></a>
 </div>

The JavaScript:

function addClassToImage(element) 
  {
    var innerImage = element.querySelector('img');
    var id  = element.id;
    if(innerImage) 
    {
      if(innerImage.classList.contains('clicked')) 
      {
        innerImage.classList.remove('clicked');
      }
      else 
      {
        innerImage.classList.add('clicked');
        console.log(id);
      }
    }
}

Upvotes: 1

Views: 5127

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115272

Based on your current code only the parent element has id attribute and you are trying to get the id of the clicked element instead of that get parent node and then its id. Where parent node reference can get using Node#parentNode property of the node.

function addClassToImage(element) {
  var innerImage = element.querySelector('img');
  // get parent node and then its id
  var id = element.parentNode.id;
 
  if (innerImage) {
    if (innerImage.classList.contains('clicked')) {
      innerImage.classList.remove('clicked');
    } else {
      innerImage.classList.add('clicked');
      console.log(id);
    }
  }
}
<div id="1" class="column">
  <a href="javascript:;" onclick="addClassToImage(this)"> f<img class="img-class" src="https://manilva.club/wp-content/uploads/2019/04/By-Product.png" alt="By Product" /></a>
</div>


UPDATE : In case you want to get the id of the closest ancestor which have id attribute then use Node#closest method along with CSS has attribute selector(as @T.J.Crowder suggested).

function addClassToImage(element) {
  var innerImage = element.querySelector('img');
  // get parent node and then its id
  var id = element.closest('[id]').id;
 
  if (innerImage) {
    if (innerImage.classList.contains('clicked')) {
      innerImage.classList.remove('clicked');
    } else {
      innerImage.classList.add('clicked');
      console.log(id);
    }
  }
}
<div id="1" class="column">
  <a href="javascript:;" onclick="addClassToImage(this)"> f<img class="img-class" src="https://manilva.club/wp-content/uploads/2019/04/By-Product.png" alt="By Product" /></a>
</div>

Upvotes: 2

Related Questions