将元素ID输出到控制台

时间:2019-04-07 16:43:37

标签: javascript

单击浏览器控制台时,我想输出一个元素的ID,但是我不知道如何以字符串格式进行输出-当前输出为空白。

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>

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);
      }
    }
}

1 个答案:

答案 0 :(得分:2)

根据您当前的代码,仅父元素具有id属性,并且您试图获取被单击元素的ID,而不是获取父节点,然后获取其ID。可以使用节点的Node#parentNode属性获得父节点引用。

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>


更新::如果要获取具有id属性的最接近祖先的id,请使用Node#closest方法和CSS has attribute selector(作为 { {3}} 建议)。

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>