Как найти id html кнопки

How to do it without inline JavaScript or external libraries

it is generally recommended to avoid inline JavaScript, but rarely is there an example of how to do it.
Here is my way of attaching events to buttons.
I’m not entirely happy with how much longer the recommended method is compared to a simple onClick attribute.

Modern browsers (2015+)

  • Works before the document has finished loading.
  • Very efficient.
  • Separates JS from HTML.
  • JS is in the <head>
const Listen = (doc) => {
    return {
        on: (type, selector, callback) => {
            doc.addEventListener(type, (event)=>{
                if(!event.target.matches(selector)) return;
                callback.call(event.target, event);
            }, false);
        }
    }
};


Listen(document).on('click', '.btn', function (e) {
    let div = document.createElement("div");
    div.innerHTML = "click " + e.target.id + "!";
    document.body.appendChild(div);
});
<button id="b1" class="btn">Button 1</button>
<button id="b2" class="btn">Button 2</button>
<button id="b3">Do nothing</button>

2014 browsers only

<button class="btn" id="b1">Button</button>
<script>
let OnEvent = (doc) => {
    return {
        on: (event, className, callback) => {
            doc.addEventListener('click', (event)=>{
                if(!event.target.classList.contains(className)) return;
                callback.call(event.target, event);
            }, false);
        }
    }
};


OnEvent(document).on('click', 'btn', function (e) {
    window.console.log(this.id, e);
});

</script>

2013 browsers only

<!DOCTYPE html>
<html>
<head>
<script>
(function(doc){
    var hasClass = function(el,className) {
        return el.classList.contains(className);
    }
    doc.addEventListener('click', function(e){
      if(hasClass(e.target, 'click-me')){
          e.preventDefault();
          doSomething.call(e.target, e);
      }
    });
})(document);

function insertHTML(str){
  var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
  lastScript.insertAdjacentHTML("beforebegin", str);
}

function doSomething(event){
  console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>

<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script>
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>

<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">

<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>

</body>
</html>

Cross-browser

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
    var cb_addEventListener = function(obj, evt, fnc) {
        // W3C model
        if (obj.addEventListener) {
            obj.addEventListener(evt, fnc, false);
            return true;
        } 
        // Microsoft model
        else if (obj.attachEvent) {
            return obj.attachEvent('on' + evt, fnc);
        }
        // Browser don't support W3C or MSFT model, go on with traditional
        else {
            evt = 'on'+evt;
            if(typeof obj[evt] === 'function'){
                // Object already has a function on traditional
                // Let's wrap it with our own function inside another function
                fnc = (function(f1,f2){
                    return function(){
                        f1.apply(this,arguments);
                        f2.apply(this,arguments);
                    }
                })(obj[evt], fnc);
            }
            obj[evt] = fnc;
            return true;
        }
        return false;
    };
    var hasClass = function(el,className) {
        return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
    }

    cb_addEventListener(doc, 'click', function(e){
      if(hasClass(e.target, 'click-me')){
          e.preventDefault ? e.preventDefault() : e.returnValue = false;
          doSomething.call(e.target, e);
      }
    });
})(document);

function insertHTML(str){
  var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
  lastScript.insertAdjacentHTML("beforebegin", str);
}

function doSomething(event){
  console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>

<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>

<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">

<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>

</body>
</html>

Cross-browser with jQuery

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function($){
    $(document).on('click', '.click-me', function(e){
      doSomething.call(this, e);
    });
})(jQuery);

function insertHTML(str){
  var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
  lastScript.insertAdjacentHTML("beforebegin", str);
}

function doSomething(event){
  console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>

<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>

<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">

<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>

</body>
</html>

You can run this before the document is ready, clicking the buttons will work because we attach the event to the document.

Here is a jsfiddle
For some strange reason the insertHTML function does not work in it even though it works in all my browsers.

You can always replace insertHTML with document.write if you don’t mind it’s drawbacks

<script>
document.write('<button class="click-me" id="btn1">Button 1</button>');
</script>

Sources:

  • What are alternatives to document.write?
  • Check if an element contains a class in JavaScript?
  • event.preventDefault() function not working in IE
  • https://gist.github.com/eduardocereto/955642

Делаю игру «Крестики нолики». Вот его HTML код —

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Tic-Tac-Toe</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <h3 id="title"></h3>

        <div class="playing-field">
            <button class="playing-field-item" id="0"></button>
            <button class="playing-field-item" id="1"></button>
            <button class="playing-field-item" id="2"></button>
            <button class="playing-field-item" id="3"></button>
            <button class="playing-field-item" id="4"></button>
            <button class="playing-field-item" id="5"></button>
            <button class="playing-field-item" id="6"></button>
            <button class="playing-field-item" id="7"></button>
            <button class="playing-field-item" id="8"></button>
        </div>

        <script src="script.js"></script>
    </body>
</html>

Как узнать id кнопки, на которую нажал игрок?

Given a set of button and the task is to determine the ID of the button when it is clicked using JavaScript and jQuery.

Get the ID of clicked button using JavaScript

Example 1: This example sets a onClick event to each button, when button is clicked, the ID of the button is passed to the function then it prints the ID on the screen. 

html

<!DOCTYPE HTML>

<html>

    <head>

        <title>

            Get the ID of the clicked button

            using JavaScript

        </title>

    </head>

    <body style = "text-align:center;">

        <h1 style = "color:green;" >

            GeeksForGeeks

        </h1>

        <p id = "GFG_UP" style =

            "font-size: 15px; font-weight: bold;">

        </p>

        <button id="1" onClick="GFG_click(this.id)">

            Button1

        </button>

        <button id="2" onClick="GFG_click(this.id)">

            Button2

        </button>

        <button id="3" onClick="GFG_click(this.id)">

            Button3

        </button>

        <p id = "GFG_DOWN" style =

            "color:green; font-size: 20px; font-weight: bold;">

        </p>

        <script>

            var el_up = document.getElementById("GFG_UP");

            var el_down = document.getElementById("GFG_DOWN");

            el_up.innerHTML = "Click on button to get ID";

            function GFG_click(clicked) {

                el_down.innerHTML = "ID = "+clicked;

            }        

        </script>

    </body>

</html>                    

Output:

Example 2: This example sets a onClick event in the <script> tag individually to each button, When button is clicked, the ID of the button is passed to the function and then print the ID on the screen. 

html

<!DOCTYPE HTML>

<html>

    <head>

        <title>

            Get the ID of the clicked button

            in JavaScript

        </title>

    </head>

    <body style = "text-align:center;">

        <h1 style = "color:green;" >

            GeeksForGeeks

        </h1>

        <p id = "GFG_UP" style =

            "font-size: 15px; font-weight: bold;">

        </p>

        <button id="1">Button 1</button>

        <button id="2">Button 2</button>

        <button id="3">Button 3</button>

        <p id = "GFG_DOWN" style =

            "color:green; font-size: 20px; font-weight: bold;">

        </p>

        <script>

            var el_up = document.getElementById("GFG_UP");

            var el_down = document.getElementById("GFG_DOWN");

            el_up.innerHTML = "Click on button to get ID";

            document.getElementById('1').onclick = GFG_click;

            document.getElementById('2').onclick = GFG_click;

            document.getElementById('3').onclick = GFG_click;

            function GFG_click(clicked) {

                el_down.innerHTML = "Button clicked, id = "

                    + this.id;

            }        

        </script>

    </body>

</html>                    

Output:

Get the ID of clicked button using jQuery

jQuery on() Method: This method adds one or more event handlers for the selected elements and child elements. 

Syntax: 

$(selector).on(event, childSelector, data, function, map)

Parameters: 

  • event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid.
  • childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.
  • data: This parameter is optional. It specifies the additional data to pass to the function.
  • function: This parameter is required. It specifies the function to run when the event occurs.
  • map: It specifies an event map ({event:func(), event:func(), …}) having one or more event to add to the selected elements, and functions to run when the events happens.

jQuery click() Method: This method triggers the click event, or adds a function to run when a click event occurs. Click event occurs when an element is clicked. 

Syntax: 

  • Trigger the click event for the selected elements: 
$(selector).click()
  • Adds a function to the click event: 
$(selector).click(function)

Parameters: This method accepts single parameter function which is optional. It specifies the function to run when the click event occurs. 

Example 1: This example sets an onClick event by using click() method to each button, When button is clicked, the ID of the button is passed to the function and then print the ID on the screen. 

html

<!DOCTYPE HTML>

<html>

    <head>

        <title>

            Get the ID of the clicked button

            using jQuery

        </title>

        <script src =

        </script>

    </head>

    <body style = "text-align:center;">

        <h1 style = "color:green;" >

            GeeksForGeeks

        </h1>

        <p id = "GFG_UP" style =

            "font-size: 15px; font-weight: bold;">

        </p>

        <button id="1"> Button1</button>

        <button id="2"> Button2</button>

        <button id="3"> Button3</button>

        <p id = "GFG_DOWN" style =

            "color:green; font-size: 20px; font-weight: bold;">

        </p>

        <script>

            $('#GFG_UP').text("Click on button to get ID");

            $("button").click(function() {

                var t = $(this).attr('id');

                $('#GFG_DOWN').text("ID = " + t);

            });                    

        </script>

    </body>

</html>                    

Output:

Example 2: This example sets an onClick event by using on() method to each button, When button is clicked, the ID of the button is passed to the function and then print the ID on the screen. 

html

<!DOCTYPE HTML>

<html>

    <head>

        <title>

            Get the ID of the clicked button

            using jQuery

        </title>

        <script src =

        </script>

    </head>

    <body style = "text-align:center;">

        <h1 style = "color:green;" >

            GeeksForGeeks

        </h1>

        <p id = "GFG_UP" style =

            "font-size: 15px; font-weight: bold;">

        </p>

        <button id="1"> Button1</button>

        <button id="2"> Button2</button>

        <button id="3"> Button3</button>

        <p id = "GFG_DOWN" style =

            "color:green; font-size: 20px; font-weight: bold;">

        </p>

        <script>

            $('#GFG_UP').text("Click on button to get ID");

            $("button").on('click',function() {

                var t = (this.id);

                $('#GFG_DOWN').text("ID = " + t);

            });                    

        </script>

    </body>

</html>                    

Output:

jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.

Last Updated :
14 Nov, 2022

Like Article

Save Article

gray animal

Sometimes, we want to get the ID of the element that we clicked on in the JavaScript click event handler.

In this article, we’ll look at how to get the ID of the clicked element in the JavaScript click handler.

Set the onclick Property of Each Element to the Same Event Handler Function

One way to let us get the ID of the element when we click on an element is to set the onclick property of each element object to the same click event handler function.

For instance, we can write the following HTML:

<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>

Then we can write the following JavaScript code to set the event handler of each element to the same click event handler:

const onClick = function() {
  console.log(this.id, this.innerHTML);
}
document.getElementById('1').onclick = onClick;
document.getElementById('2').onclick = onClick;
document.getElementById('3').onclick = onClick;

The onClick function is the event handler for clicks of each button.

this is the element that we clicked on.

We can get the id property to get the ID of the element that’s clicked on.

And innerHTML has the button’s content.

Then we assign the onClick function as the value of the onclick property to each button element.

Therefore, when we click on the Button 1 button, we get:

'1' 'Button 1'

logged.

When we click on the Button 2 button, we get:

'2' 'Button 2'

And when we click on the Button 3 button, we get:

'3' 'Button 3'

logged.

Getting the Element Clicked on from the Event Object

Another way to get the element we clicked on in the event handler is to get it from the event object which is the first parameter in the event handler function.

For instance, we can write the following HTML:

<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>

And the following JavaScript code:

const onClick = (event) => {
  console.log(event.srcElement.id);
}
window.addEventListener('click', onClick);

We call window.addEventListener to attach the click event listener to the html element.

Then we get the element that’s clicked on from the event.srcElement property.

And we can get the ID of that element with the id property.

We can replace event.srcElement with event.target :

const onClick = (event) => {
  console.log(event.target.id);
}
window.addEventListener('click', onClick);

and we get the same result.

We can also check if the element we clicked on is a button with the nodeName property.

For instance, we can write:

const onClick = (event) => {
  if (event.target.nodeName === 'BUTTON') {
    console.log(event.target.id);
  }
}
window.addEventListener('click', onClick);

to add an if statement to check if event.target.nodeName is 'BUTTON' before running the console.log method.

This way, we only run the click handler code if we clicked on a button.

Conclusion

We can get the ID of the element that’s clicked from the click event handler.

We can either get the value from this if we use a regular function.

Or we can get the same value from the event object of the click event handler.

Web developer specializing in React, Vue, and front end development.

View Archive

  1. Get Clicked Button ID With the This.id Method in JavaScript
  2. Get Clicked Button ID With the Event.target.id Method in JavaScript
  3. Get Clicked Button ID With the addEventListener Function in JavaScript
  4. Get Clicked Button With jQuery

Get onClick Button ID in JavaScript

This tutorial presents how to get the ID of a clicked button in four different methods. These methods are this.id, event.target.id, addEventListener, and jQuery.

Get Clicked Button ID With the This.id Method in JavaScript

You’ll do this by creating a function that gets activated when you click the button. So when you click the button, the function will receive the button ID via this.id.

Although the value of this depends on how it’s called. In this case, it’ll refer to the button and its properties, like the button ID.

<body>
    <main>
        <button id="first_button" onclick="getClickID(this.id)">First Button</button>
        <button id="second_button" onclick="getClickID(this.id)">Second Button</button>
        <button id="third_button" onclick="getClickID(this.id)">Third Button</button>
    </main>

    <script type="text/javascript">
        function getClickID(clickID) {
            alert(clickID);
        }
    </script>
</body>

Output:

Get Clicked Button ID With This.id Method

We have three buttons with different IDs with an onclick event attribute in the code block above. The value of the onclick event attribute is a function whose argument is this.id or the button ID.

Get Clicked Button ID With the Event.target.id Method in JavaScript

You can get a button ID during a click event thanks to the target property of the Event interface. The target property refers to the button element that got the click event from the user.

At the same time, you can get the ID of the button from the target property via target.id. In the code example below, we’ve created a function that uses event.target.id to show the ID of the clicked button.

<body>
    <main>
        <button id="button_1" onclick="getClickID()">Button_1</button>
        <button id="button_2" onclick="getClickID()">Button_2</button>
        <button id="button_3" onclick="getClickID()">Button_3</button>
    </main>

    <script type="text/javascript">
        function getClickID() {
            alert(event.target.id);
        }
    </script>
</body>

Output:

Get Clicked Button ID With Event.target.id Method

Get Clicked Button ID With the addEventListener Function in JavaScript

You can implement a custom function that utilizes an event listener to get the ID of an element. This will be the element that fires an event.

Put the custom function in your web page’s <head> section. This way, it becomes available before the rest of the web page downloads.

In the following code, we’ve used the custom function to add click events to the set of buttons. So, when you run the code in your web browser, you’ll get a JavaScript alert message that shows the button ID.

<head>
    <script type="text/javascript">
        const customEvent = (documentObject) => {
            return {
                on: (event_type, css_selector, callback_function) => {
                    documentObject.addEventListener(event_type, function (event) {
                        if (event.target.matches(css_selector) === false) return;
                        callback_function.call(event.target, event);
                    }, false);
                }
            }
        }
        customEvent(document).on('click', '.html-button', function (event) {
            alert(event.target.id);
        });
    </script>
</head>
<body>
    <main>
        <button id="btn_1" class="html-button">Code-1</button>
        <button id="btn_2" class="html-button">Code-2</button>
        <button id="btn_3" class="html-button">Code-3</button>
    </main>
</body>

Output:

Get Clicked Button ID With addEventListener Function

Get Clicked Button With jQuery

This approach is like the first example in this article, but we’ll use jQuery. jQuery provides the click function that you can attach to an element to get the element’s ID via this.id.

The code below has buttons that have IDs and class attributes. We use jQuery to grab the button class names, and we attach a click event to all, and when you click any button, you’ll get its ID in an alert window in your web browser.

<body>
    <main>
        <button id="btn_one" class="clicked-button">CK-button-1</button>
        <button id="btn_two" class="clicked-button">CK-button-2</button>
        <button id="btn_three" class="clicked-button">CK-button-3</button>
    </main>

    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
        integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"
        referrerpolicy="no-referrer"
    >
    </script>
    <script>
        $('.clicked-button').click(function(){
            alert(this.id);
        })
    </script>
</body>

Output:

Get Clicked Button With jQuery

Понравилась статья? Поделить с друзьями:
  • Как найти сечение провода формула по сопротивлению
  • Как найти числа пифагора
  • Как найти технику по ключу
  • Как найти метастазы в позвоночнике
  • Как правильно составить презентацию проекта пример