Risposte:
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);
}
myDOMElement.idpuò anche restituire un elemento figlio con l'id o il nome di "id". Come visto qui in questo jsfiddle
Sì, puoi semplicemente dire:
function getID(oObject)
{
var id = oObject.id;
alert("This object's ID attribute is set to \"" + id + "\".");
}
Dai un'occhiata: Attributo ID | Proprietà id
Funzionerebbe anche questo:
document.getElementsByTagName('p')[0].id
(Se elemento in cui il primo paragrafo del documento)
getElementsByClassNamenon è supportato in IE (prima di IE9).
Super Easy Way è
$('.CheckBxMSG').each(function () {
var ChkBxMsgId;
ChkBxMsgId = $(this).attr('id');
alert(ChkBxMsgId);
});
Dimmi se questo aiuta
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>
È 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;
};
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