get an element's id

JavascriptHtml

Javascript Problem Overview


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

element.getAttribute('id')

Javascript Solutions


Solution 1 - Javascript

Yes you can just use the .id property of the dom element, for example:

myDOMElement.id

Or, something like this:

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

Solution 2 - Javascript

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

Solution 3 - Javascript

This would work too:

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

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

Solution 4 - Javascript

Super Easy Way is

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

Tell me if this helps

Solution 5 - Javascript

In events handler you can get id as follows

function show(btn) {
  console.log('Button id:',btn.id);
}

<button id="myButtonId" onclick="show(this)">Click me</button>

Solution 6 - Javascript

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;
};

Solution 7 - Javascript

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

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

Solution 8 - Javascript

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRanaView Question on Stackoverflow
Solution 1 - JavascriptNick CraverView Answer on Stackoverflow
Solution 2 - JavascriptMorteza ManaviView Answer on Stackoverflow
Solution 3 - JavascriptdonohoeView Answer on Stackoverflow
Solution 4 - JavascriptTj LaubscherView Answer on Stackoverflow
Solution 5 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 6 - JavascriptXavier Felipe MedinaView Answer on Stackoverflow
Solution 7 - JavascriptJesper EngbergView Answer on Stackoverflow
Solution 8 - JavascriptunixmiahView Answer on Stackoverflow