Home  >  Article  >  Web Front-end  >  Is the id unique in the html document?

Is the id unique in the html document?

青灯夜游
青灯夜游Original
2021-12-14 11:15:163949browse

id must be unique within the HTML document. In an HTML document, any element (node) has an id attribute. The id attribute is the unique identifier of the node and is the "unique" identifier when specifying DOM operations for a node, so the id value cannot be repeated in the same document; If the identifier is not unique, it will cause trouble when operating the DOM.

Is the id unique in the html document?

The operating environment of this tutorial: Windows 7 system, HTML5 version, Dell G3 computer.

The id attribute specifies the unique id of the HTML element.

id must be unique within the HTML document.

In an HTML document, any element (node) has an id attribute. The id attribute is the unique identifier of the node. It is the "unique" identifier when specifying a DOM operation for a node, so the same document The id value cannot be repeated.

ID has nothing to do with how the page is rendered. Whether the rendering is correct depends on the document structure and style (here is a style rule written by you in the browser's default style sheet), so it can be displayed normally.

But not unique identifiers will cause trouble during DOM operations.

<html>
<head>

<style type="text/css">
#txtName {background:red;}
</style>

<script type="text/javascript">

function GetValue()
{
var a = document.getElementById(&#39;txtName&#39;).value;
alert(a);
}

</script>
</head>
<body >

姓名:<input type="text" id="txtName" /> </br>

密码:<input type="text" id="txtName" /> </br>

<input type="button" value="获取id=txtName的文本框的值" onclick="GetValue();" />

</body>
</html>

Among them:

var a = document.getElementById(&#39;txtName&#39;).value;

Get the value of the tag ID="txtName". The result is that the value of the first text box pops up, indicating that the browser Just take the value of the first tag with this ID. The rendering is as follows:

Is the id unique in the html document?

Summary: If there are the same IDs, javascript will only take the first one with this ID. ID tag.

Recommended tutorial: "html video tutorial"

The above is the detailed content of Is the id unique in the html document?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn