有没有其他方法来获取DOM元素的ID?
element.getAttribute('id')
是的,你可以简单地说:
function getID(oObject)
{
var id = oObject.id;
alert("This object's ID attribute is set to \"" + id + "\".");
}
看这个: ID 属性 | id 属性
这也可以运行:
document.getElementsByTagName('p')[0].id
(如果元素是文档中的第一个段落)
getElementsByClassName
在IE9及之前的版本不被支持。 - user113716 $('.CheckBxMSG').each(function () {
var ChkBxMsgId;
ChkBxMsgId = $(this).attr('id');
alert(ChkBxMsgId);
});
在事件句柄中,您可以按照以下方式获取id:
function show(btn) {
console.log('Button id:',btn.id);
}
<button id="myButtonId" onclick="show(this)">Click me</button>
const getIdFromDomObj = function(domObj){
const { id } = domObj;
const isIdString = typeof id === 'string';
if(!isIdString) return;
return id;
};
这个代码获取并弹出具有"id"为"ele"的元素的id。
var id = document.getElementById("ele").id;
alert("ID: " + id);
console.log(id.id)
<p id="id">
document.getElementById
来获取一个元素的ID。如果找到了,它将返回一个元素节点,否则返回null
。var x = document.getElementById("elementid"); // Get the element with id="elementid"
x.style.color = "green"; // Change the color of the element
myDOMElement.id
也可能返回具有ID或名称为“id”的子元素。如此处所示 在这个jsfiddle中。 - bhattamer