Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
DOM

How to Check Whether an HTML Element Has an `id` Attribute

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use element.hasAttribute("id") when you need to know whether a DOM element contains an id attribute:

if (element.hasAttribute("id")) {
  // The id attribute is present.
}

In JavaScript, “element” is more precise than “tag”: a tag is markup such as <div>, while your code works with the corresponding DOM element object.

Choose the check that matches your goal

What you need Use Result
Test whether the attribute exists element.hasAttribute("id") true or false; distinguishes a missing attribute from id=""
Read the value and detect absence element.getAttribute("id") A string, or null when no id attribute exists
Read the reflected ID property element.id The ID as a string; both a missing attribute and an empty value appear as ""
Find an element when its ID is known document.getElementById("name") The matching element from the document, not a presence test on an existing element

Test for the attribute with hasAttribute()

hasAttribute() returns a Boolean and is the clearest presence check:

const card = document.querySelector(".card");

if (card && card.hasAttribute("id")) {
  console.log("This element has an id attribute.");
}

The selector may return null, so check the element before calling its method. If you already have a DOM element from another operation, call hasAttribute("id") directly on it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Read the ID and distinguish missing from empty

Use getAttribute() when you need the attribute’s value as well as its missing state:

const value = element.getAttribute("id");

if (value !== null) {
  console.log("The attribute exists. Its value is:", value);
}

For <div></div>, the result is null. For <div id=""></div>, the result is an empty string. That distinction matters when an attribute may be present but empty.

Require a non-empty ID

If your requirement is specifically a usable, non-empty value, test both conditions:

const hasNonEmptyId =
  element.hasAttribute("id") && element.getAttribute("id") !== "";

The HTML id global attribute is intended to identify an element. A non-empty ID should be unique within its document tree, as described by MDN’s id reference and the WHATWG HTML Standard.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the id property for a convenient value

The reflected id property is concise when you only need the current ID string:

if (element.id !== "") {
  console.log(element.id);
}

Unlike hasAttribute(), this does not tell you whether the attribute is present but empty: both a missing attribute and id="" produce an empty string. See MDN’s documentation for Element.id.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Find an element by a known ID

When you know the ID and want to locate the element, use document.getElementById():

const panel = document.getElementById("settings-panel");

if (panel !== null) {
  // An element with that id was found.
}

This performs a document lookup; it is different from asking an existing element whether it has an id attribute. IDs should not be duplicated. If duplicates exist, getElementById() returns the first matching element. See MDN’s getElementById() reference.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use IDs safely in CSS selectors

An ID can be valid as an HTML attribute value without being valid CSS identifier syntax. If you interpolate an ID into querySelector() or a stylesheet selector, escape it first:

const rawId = element.getAttribute("id");

if (rawId !== null) {
  const match = document.querySelector(`#${CSS.escape(rawId)}`);
}

CSS.escape() prevents special characters in the attribute value from breaking the selector. If you only need the element by its known ID, getElementById() avoids CSS selector parsing altogether.

Quick decision guide

  • Need only presence, including an empty attribute? Use hasAttribute("id").
  • Need the value and a reliable missing check? Use getAttribute("id") and compare with null.
  • Need a concise string and an empty value is acceptable? Read element.id.
  • Need to locate an element from a known ID? Use document.getElementById().

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.