Javascript 获取元素的 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3623110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:28:09  来源:igfitidea点击:

get an element's id

javascripthtml

提问by Rana

Is there another way to get an DOM element's ID?

有没有另一种方法来获取 DOM 元素的 ID?

element.getAttribute('id')

回答by Nick Craver

Yes you can just use the .idpropertyof the dom element, for example:

是的,你可以只使用.id属性的的DOM元素,例如:

myDOMElement.id

Or, something like this:

或者,像这样:

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

回答by Morteza Manavi

Yes you can simply say:

是的,你可以简单地说:


function getID(oObject) 
{
    var id = oObject.id;
    alert("This object's ID attribute is set to \"" + id + "\"."); 
}

Check this out: ID Attribute | id Property

看看这个: ID 属性 | id 属性

回答by donohoe

This would work too:

这也可以:

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

(If element where the 1st paragraph in your document)

(如果元素位于文档中的第一段)

回答by Tj Laubscher

Super Easy Way is

超级简单的方法是

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

Tell me if this helps

告诉我这是否有帮助

回答by Kamil Kie?czewski

In events handler you can get id as follows

在事件处理程序中,您可以按如下方式获取 id

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

回答by Xavier Felipe Medina

You need to check if is a string to avoid getting a child element

您需要检查是否是字符串以避免获取子元素

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

回答by Jesper Engberg

This gets and alerts the id of the element with the id "ele".

这将获取并提醒 id 为“ele”的元素的 id。

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

回答by unixmiah

Yes. You can get an element by its ID by calling document.getElementById. It will return an element node if found, and nullotherwise:

是的。您可以通过调用document.getElementById. 如果找到,它将返回一个元素节点,null否则:

var x = document.getElementById("elementid");   // Get the element with id="elementid"
x.style.color = "green";                        // Change the color of the element