最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How do I get the id of clicked element using pure javascript? - Stack Overflow

programmeradmin0浏览0评论

This is the HTML code which has 3 divs with same class name and one with a different class name. I want to write a (pure) JavaScript function that has to return me the value of respective custom-id of the div only when I clicked on the div element with class div1.I want to invoke the onclick event from the JavaScript as well.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>

</head>

<body>
  <div style="width: 100px; height: 100px; background: green;" class="div1" data-custom-id="123">Some text</div>
  <div style="width: 100px; height: 100px; background: red;" class="div1" data-custom-id="456">Some more text</div>
  <div style="width: 100px; height: 100px; background: green;" class="div1" data-custom-id="1223">More text</div>
  <div style="width: 100px; height: 100px; background: red;" class="div2" data-custom-id="4526">Seperate div</div>
  <script>
    (function() {

      let displayedId = [];
      let len = document.getElementsByClassName('div1');
      for (var i = 0; i < length; i++) {
        displayedId.push((len[i].getAttribute('data-custom-id')));
      }
    })();
  </script>
</body>

</html>

This is the HTML code which has 3 divs with same class name and one with a different class name. I want to write a (pure) JavaScript function that has to return me the value of respective custom-id of the div only when I clicked on the div element with class div1.I want to invoke the onclick event from the JavaScript as well.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>

</head>

<body>
  <div style="width: 100px; height: 100px; background: green;" class="div1" data-custom-id="123">Some text</div>
  <div style="width: 100px; height: 100px; background: red;" class="div1" data-custom-id="456">Some more text</div>
  <div style="width: 100px; height: 100px; background: green;" class="div1" data-custom-id="1223">More text</div>
  <div style="width: 100px; height: 100px; background: red;" class="div2" data-custom-id="4526">Seperate div</div>
  <script>
    (function() {

      let displayedId = [];
      let len = document.getElementsByClassName('div1');
      for (var i = 0; i < length; i++) {
        displayedId.push((len[i].getAttribute('data-custom-id')));
      }
    })();
  </script>
</body>

</html>

Share Improve this question edited Dec 21, 2023 at 14:17 Heretic Monkey 12.1k7 gold badges61 silver badges131 bronze badges asked Mar 9, 2018 at 19:05 Anil PoudelAnil Poudel 311 silver badge4 bronze badges 5
  • 5 What research have you done? Where is the code you have tried? Did you bother to search out click events? This is not a code writing service. Posting some markup and then asking someone to show you some code is not acceptable here. – gforce301 Commented Mar 9, 2018 at 19:08
  • add a click event handler onto the elements, and then use this.id inside the listener to get the id of it. – George Commented Mar 9, 2018 at 19:10
  • Also see: Using data attributes. – showdev Commented Mar 9, 2018 at 19:11
  • I remend you this site, Vanilla JS isn't that hard to learn, specially if you are only doing such easy things – Gustavo Topete Commented Mar 9, 2018 at 19:22
  • Does this answer your question? Get ID of element clicked – Nico Haase Commented May 22, 2023 at 6:13
Add a ment  | 

6 Answers 6

Reset to default 5

You'll have to add an event listener to every element of that class, like this:

var divs = document.querySelectorAll(".div1");

var clickFunction = function(event){
    var id = event.target.attributes['define-custom-id'].value;
    alert(id);
};

for (var i = 0; i < divs .length; i++) {
    divs[i].addEventListener('click', clickFunction , false);
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>

</head>

<body>
  <div style="width: 100px; height: 100px; background: green;" class="div1" define-custom-id="123">Some text</div>
  <div style="width: 100px; height: 100px; background: red;" class="div1" define-custom-id="456">Some more text</div>
  <div style="width: 100px; height: 100px; background: green;" class="div1" define-custom-id="1223">More text</div>
  <div style="width: 100px; height: 100px; background: red;" class="div2" define-custom-id="4526">Seperate div</div>
</body>

</html>

Your elements don't have id , so you can't simply do e.target.id. I'd remend that you use data-* attributes instead, as they are accepted in HTML5 standards.

Like this:

var divs = document.querySelectorAll(".div1");

var clickFunction = function(event){
    var id = event.target.dataset.customId;
    alert(id);
};

for (var i = 0; i < divs .length; i++) {
    divs[i].addEventListener('click', clickFunction , false);
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>

</head>

<body>
  <div style="width: 100px; height: 100px; background: green;" class="div1" data-custom-id="123">Some text</div>
  <div style="width: 100px; height: 100px; background: red;" class="div1" data-custom-id="456">Some more text</div>
  <div style="width: 100px; height: 100px; background: green;" class="div1" data-custom-id="1223">More text</div>
  <div style="width: 100px; height: 100px; background: red;" class="div2" data-custom-id="4526">Seperate div</div>
</body>

</html>

Try this:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <div style="width: 100px; height: 100px; background: green;" class="myDivs div1" define-custom-id="123">Some text</div>
    <div style="width: 100px; height: 100px; background: red;" class="myDivs div1" define-custom-id="456">Some more text</div>
    <div style="width: 100px; height: 100px; background: green;" class="myDivs div1" define-custom-id="1223">More text</div>
    <div style="width: 100px; height: 100px; background: red;" class="myDivs div2" define-custom-id="4526">Seperate div</div> 

    <script>
        var myDivs = document.getElementsByClassName('myDivs');

        for(var i = 0; i < myDivs.length; i++) {
            myDivs[i].addEventListener('click', function (event) {
                alert(this.getAttribute("define-custom-id"));
            });
        }       
    </script>
</body>
</html>

Pass the ID as function parameter.

  <div id="1" onClick="click_me(this.id)">Div 1</div>
  <div id="2" onClick="click_me(this.id)">Div 2</div>
  <div id="3" onClick="click_me(this.id)">Div 2</div>

   <script type="text/javascript">
    function click_me(clicked_id)
    {
        console.log(clicked_id);
    }
  </script>

An you can recive the id in function

    function click_me(clicked_id)
    {
        console.log(clicked_id);
    }
    <div id="1" onClick="click_me(this.id)">Div 1</div>
    <div id="2" onClick="click_me(this.id)">Div 2</div>
    <div id="3" onClick="click_me(this.id)">Div 2</div>
 

It's easy to achieve, look at my snippet:

document.addEventListener('readystatechange',()=>{
  if(document.readyState=='interactive'){
    document.addEventListener('click',(event)=>{
      console.log(event.target.getAttribute('define-custom-id'));
    }) 
  }
});
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	
</head>
<body>
	<div style="width: 100px; height: 100px; background: green;" class="div1" define-custom-id="123">Some text</div>
	<div style="width: 100px; height: 100px; background: red;" class="div1" define-custom-id="456">Some more text</div>
	<div style="width: 100px; height: 100px; background: green;" class="div1" define-custom-id="1223">More text</div>
	<div style="width: 100px; height: 100px; background: red;" class="div2" define-custom-id="4526">Seperate div</div> 
</body>
</html>

This is the part that does it all:

document.addEventListener('click',(event)=>{
      console.log(event.target.getAttribute('define-custom-id'));
    }) 

The other part is the equivalent in jquery of:

$(document).ready()

Or you can do this. Write onclick function which will return id of element whenever click.

function fun(){
  console.log(event.target.attributes['define-custom-id'].value);
}
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	
</head>
<body>
	<div style="width: 100px; height: 100px; background: green;" class="div1" define-custom-id="123" onclick="fun(this)">Some text</div>
	<div style="width: 100px; height: 100px; background: red;" class="div1" define-custom-id="456" onclick="fun(this)">Some more text</div>
	<div style="width: 100px; height: 100px; background: green;" class="div1" define-custom-id="1223" onclick="fun(this)">More text</div>
	<div style="width: 100px; height: 100px; background: red;" class="div2" define-custom-id="4526" onclick="fun(this)">Seperate div</div> 
</body>
</html>

Looks like someone already provided this route but will be the easiest -

function getCustomID(){
    var results = event.target.attributes['data-custom-id'].value;
    console.log(results);
    return results;
}
<body>
    <div class="box" data-custom-id="123" onclick="getCustomID(this)">Click Me</div>
    <div class="box" data-custom-id="456" onclick="getCustomID(this)">Click Me</div>
    <div class="box" data-custom-id="789" onclick="getCustomID(this)">Click Me</div>
    <div class="box" data-custom-id="000" onclick="getCustomID(this)">Click Me</div>
</body>

发布评论

评论列表(0)

  1. 暂无评论