How to get the ID value of a button?

Asked

Viewed 576 times

0

In the ID there is a dynamic value, so I would like to get that value without just clicking map the button and store in a var:

<button name="edit" id="valor_dinamico">Edit</button>
  • 1

    How many buttons like that do you have? Only 1?

  • and how will you identify which is exactly that button that wants to know the id if it has multiple buttons on the page? will click on it?

  • Only with the information you gave is it not possible to give an answer that always works.

3 answers

3

You can use the querySelector as mentioned in the other answer, and select the button named "Edit":

console.log("id=" + document.querySelector('button[name="edit"]').id)
<button name="edit" id="valor_dinamico">Edit</button>

2

To obtain the id dynamically can be used the command below in Javascript:

botao = document.querySelector(".classe-pai button")
id = botao.id

id will be with the value of this tag because a css query was performed that follows the following rule: Given a class element parent class the child who is the first tag button will be selected.

The query rules are the same for the css query in the html document.

That is, another valid example would be #id-do-parent button

To learn more: https://www.w3schools.com/jsref/met_document_queryselector.asp

2


I don’t know if that’s exactly it, but making a forEach You can catch them all ID of all the Buttons and in order to get the value of the ID you use the .id as I did in the model below.

Vase wants the id to be a variable you can store it with let idd = e.id for example. I left this part commented in the code below, but the result of the printing is the same

function x() {
    let bt = document.querySelectorAll('button');

    bt.forEach((e) => {

        console.log('O ID é: ' + e.id);
        
        //se quiser colocar o ID em uma variável e depois imprimir
        //let idd = e.id 
        //console.log(idd);
    })
}

x()
<button id="bt1">btn1</button>
<button id="bt2">btn2</button>
<button id="bt3">btn3</button>
<button id="bt4">btn4</button>

  • but in that case, how to know that is that specific button?

  • @Ricardopunctual I think I understood the question a little different from you, for me "a button " would be any button, or all buttons... Already to get the button he wants there are a thousand ways to select, including by the father, but the father is the body. If you see the code there it is very basic, just a didactic example... I tried to make tbm a different answer from the others since the AP did not give many details

  • I understood your point, I just kept thinking about the *"ID of a button?" which in this case would be different from "all" the buttons, but anyway I think this is because of how the question was written, is not clear

Browser other questions tagged

You are not signed in. Login or sign up in order to post.