Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
HTML

How to Get the Name of an HTML Element in XPath

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

Use the XPath name() function. With no argument, it returns the qualified name (QName) of the current context node; with an expression such as name(//body), it returns the name of the first node selected. If you need the tag’s local name without a namespace prefix, use local-name(). For namespace-independent matching, combine local-name() with namespace-uri().

The direct answer: name()

The shortest XPath expression is:

name()

That asks for the QName of the current context node. You can also pass a node selection:

name(//body)

The result is the name of the first body element in document order. MDN defines name() as returning a string for the first node in the supplied node-set; when no node-set is supplied, the context node is used. See the MDN name() reference for the function’s XPath 1.0 behavior.

Common examples

  • name() — the current node’s qualified name.
  • name(//body) — the qualified name of the first element selected by //body.
  • name(/*) — the qualified name of the document element.

A QName can include a namespace prefix. Therefore, the returned string is not always just the visible tag text you expect from a simple HTML document.

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

When to use local-name() instead

If you want only the local part of an element name, use:

local-name()

For example:

local-name(/*)

This returns the local name of the document element without its namespace prefix. Like name(), local-name() uses the context node when no argument is supplied, or the first node from an expression when you pass one.

Choose the function based on the value your code needs:

Need Expression Returned value
Qualified name, including a prefix when one is present name() The context node’s QName
Qualified name of a selected node name(//body) The QName of the first selected node
Local name only local-name() The local component, without a prefix
Local name of the document element local-name(/*) The document element’s local name

Namespaces change what “the name” means

In a namespaced document, a prefix is only an alias for a namespace binding. Two elements can display the same prefix or local name while belonging to different namespaces, and the same namespace can use different prefixes in different documents. XPath 3.1 describes an expanded QName as a prefix, a local name and a namespace URI; the W3C XPath 3.1 Recommendation defines that model.

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

Use name() when the qualified name itself is what you need. Use local-name() when prefixes should not matter. If identity must be tied to a particular vocabulary, test both the local name and namespace URI:

//*[local-name() = 'p' and namespace-uri() = 'http://www.w3.org/1999/xhtml']

This selects elements whose local name is p and whose namespace URI is the XHTML URI shown in the expression. Replace that URI with the namespace actually used by your document and XPath engine.

Why a plain element test can miss namespaced HTML

In browser XPath, an unprefixed element name test does not automatically match elements in a default namespace. An expression such as //p can therefore fail when the document uses a default namespace. A namespace resolver, where the host API provides one, or an explicit local-name() plus namespace-uri() test avoids relying on a particular prefix.

Using the functions in predicates

The functions can be used inside a predicate when you need to filter nodes by the name returned at that point:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
XPath 2.0 Programmer's Reference
  • Used Book in Good Condition
//*[name() = 'div']

That expression selects elements whose returned QName is exactly div. It is appropriate for a document where the target elements have that QName. If prefixes may vary, compare the local name and namespace instead:

//*[local-name() = 'p' and namespace-uri() = 'http://www.w3.org/1999/xhtml']

The distinction matters because comparing only a local name can combine elements from unrelated vocabularies, while comparing only a prefix can break when the document binds that namespace under another prefix.

Getting an element name in browser JavaScript

Browsers expose XPath through document.evaluate(). The call returns an XPathResult; request a string result when evaluating name() or local-name():

const result = document.evaluate(
  'name(/*)',
  document,
  null,
  XPathResult.STRING_TYPE,
  null
);
console.log(result.stringValue);

To obtain the local name instead, change the expression:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const result = document.evaluate(
  'local-name(/*)',
  document,
  null,
  XPathResult.STRING_TYPE,
  null
);
console.log(result.stringValue);

For a selected element, pass a node-returning expression to the function:

const result = document.evaluate(
  'name(//body)',
  document,
  null,
  XPathResult.STRING_TYPE,
  null
);
console.log(result.stringValue);

The namespace resolver argument is null in these simple examples. When your XPath contains prefixes for a namespaced XML vocabulary, provide a resolver appropriate to that document, or use explicit namespace tests when that is safer for the host API.

Context nodes, selected nodes and the first-node rule

No argument: inspect the current context

name() and local-name() operate on the current context when called without an argument. The context is supplied by the XPath host—such as the node against which an expression is evaluated—so the same expression can return different names when evaluated from different nodes.

Argument supplied: inspect a selection

With an argument, the function receives a node-set expression:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
name(//section)

If that expression selects several nodes, the function returns the name for the first node in document order, not a list of every name. If your goal is to inspect each node separately, select the nodes themselves and evaluate the function once per node in the host language rather than expecting one string to contain all results.

Element name versus visible text

These functions report node names, not the text inside an element. For example, an element containing “Sign in” still has a name such as button; extracting “Sign in” is a different XPath operation. Keeping the two tasks separate prevents a selector that finds text from being mistaken for one that identifies the element type.

Practical recipes

Read the root element’s qualified name

name(/*)

Use this when you need the document element’s QName.

Read the root element’s local name

local-name(/*)

Use this when a namespace prefix should not appear in the result.

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

Match an unprefixed HTML element by QName

//*[name() = 'div']

This is a literal QName comparison. It is most predictable when the document’s elements are unprefixed in the XPath data model.

Match by namespace regardless of prefix

//*[local-name() = 'p' and namespace-uri() = 'http://www.w3.org/1999/xhtml']

This checks both parts of the identity and does not require your expression to guess which prefix the document used.

Inspect an explicitly selected node in JavaScript

const result = document.evaluate(
  'name(//body)',
  document,
  null,
  XPathResult.STRING_TYPE,
  null
);
const qualifiedName = result.stringValue;

Use qualifiedName wherever your application needs the returned string.

Choosing the right expression

Question Best starting point Reason
What is this context element called? name() Uses the context node and preserves the QName.
What is the name of the first node selected by this path? name(path) Evaluates the path, then reports the first node’s QName.
What tag name should I compare without caring about prefixes? local-name() Returns only the local component.
How do I distinguish same-named elements from different vocabularies? local-name() + namespace-uri() Tests both the local name and namespace identity.

Troubleshooting XPath name lookups

The result includes a prefix

That is expected from name(): it returns a QName. Use local-name() when the prefix is not part of the value you want.

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

The expression finds the wrong node

Check whether the argument selects more than one node. name(path) reports only the first node in the supplied node-set. Narrow the path or iterate over the selected nodes in your host language.

//p does not match namespaced content

In browser XPath, unprefixed tests do not automatically match elements in a default namespace. Use a namespace resolver for prefixed expressions, or test local-name() and namespace-uri() explicitly.

Elements from different vocabularies are mixed together

A local name alone is not a complete identity. Add a namespace-uri() condition with the URI for the vocabulary you intend to match.

JavaScript gives an unexpected result type

document.evaluate() returns an XPathResult. Request XPathResult.STRING_TYPE for name functions and read stringValue; use a node-oriented result type only when you actually need the selected nodes.

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

The expression works in one XPath host but not another

The functions described here are documented in MDN’s XPath 1.0 references, while browser integration is provided by the DOM XPath API. Host APIs can differ in how they supply context nodes, namespace resolvers and result types. Verify those host-specific arguments instead of assuming every XPath engine exposes the same API or language version.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your real goal is to obtain a clean rendering of a page before inspecting its HTML, ScreenshotNeo provides a website screenshot API and MCP server. You still use XPath in your own parser when you need element names, but you do not have to build and maintain a browser-capture pipeline first.

One GET request returns a PNG, JPEG, WebP or PDF. The API accepts the URL and access key as query parameters:

See the ScreenshotNeo API documentation for the complete option list.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
  • Cookie and consent banners, newsletter popups and chat widgets are removed before the shot; more than 60 known consent platforms are covered, and each cleanup step can be disabled.
  • Bot checks and CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed. Response headers identify the page verdict and billing result with X-Page-Verdict and X-Billed.
  • An MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients, so AI agents can perform captures.
  • The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan.

Create a free ScreenshotNeo account to get the 1,000-shot allowance without entering a card.

FAQ

Does name() return an HTML tag in uppercase?

The function returns the QName represented by the XPath data model and host parser. Do not normalize its case or prefix unless your application explicitly requires a particular display format.

Can a namespace URI be empty?

Yes. namespace-uri() returns an empty string for a node without a namespace; it also returns an empty string for non-element and non-attribute nodes.

Is name() limited to elements?

No. It reports the name of the first node supplied, so the node kind and the host document model still matter when you apply it outside ordinary element selections.

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.

Frequently Asked Questions

Does name() return an HTML tag in uppercase?

It returns the QName represented by the XPath data model and host parser. Normalize case or prefixes only if your application requires a specific display format.

Can a namespace URI be empty?

Yes. namespace-uri() returns an empty string for a node without a namespace, and also for non-element and non-attribute nodes.

Is name() limited to elements?

No. It reports the name of the first supplied node, so the node kind and host document model matter when you use it outside ordinary element selections.

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.

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

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
Windows Errors? Fix Them Before They SpreadFree repair scan
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.