ottenere l'ID di un elemento


186

C'è un altro modo per ottenere l'ID di un elemento DOM?

element.getAttribute('id')

Risposte:


290

Sì, è possibile utilizzare solo la .idproprietà del elemento DOM , ad esempio:

myDOMElement.id

O qualcosa del genere:

var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
  alert(inputs[i].id);
}

3
@Rana - Sì, è una proprietà dell'elemento DOM e tutti gli elementi specifici ereditano dall'elemento dom di base, quindi hanno la proprietà :)
Nick Craver

18
Sii stanco di questo perché myDOMElement.idpuò anche restituire un elemento figlio con l'id o il nome di "id". Come visto qui in questo jsfiddle
bhattamer,


15

Funzionerebbe anche questo:

document.getElementsByTagName('p')[0].id

(Se elemento in cui il primo paragrafo del documento)


getElementsByClassNamenon è supportato in IE (prima di IE9).
user113716

È stato un errore. Significava "getElementByTagName" per aver a che fare con un tag
donohoe,

4

Super Easy Way è

  $('.CheckBxMSG').each(function () {
            var ChkBxMsgId;
            ChkBxMsgId = $(this).attr('id');
            alert(ChkBxMsgId);
        });

Dimmi se questo aiuta


1

Nel gestore eventi è possibile ottenere l'ID come segue

function show(btn) {
  console.log('Button id:',btn.id);
}
<button id="myButtonId" onclick="show(this)">Click me</button>


0

È necessario verificare se è una stringa per evitare di ottenere un elemento figlio

var getIdFromDomObj = function(domObj){
   var id = domObj.id;
   return typeof id  === 'string' ? id : false;
};

-2

Questo ottiene e avvisa l'id dell'elemento con l'id "ele".

var id = document.getElementById("ele").id;
alert("ID: " + id);

10
se conosci id, qual è la necessità di queste righe?
shafeeq

A scopo illustrativo. Il codice non deve sempre essere reale.
Graham,

-4

Sì. Puoi ottenere un elemento tramite il suo ID chiamando document.getElementById. Restituirà un nodo elemento se trovato, e nullaltrimenti:

var x = document.getElementById("elementid");   // Get the element with id="elementid"
x.style.color = "green";                        // Change the color of the element
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.