HTML DOM Base 对象

htmlweb developmentfront end technology更新于 2025/9/21 14:36:17

HTML DOM Base 对象与 HTML <base> 元素关联。<base> 元素用于指定 HTML 文档中所有其他 URL 的基准 URL。一个 HTML 文档中最多只能有一个 <base> 元素。Base 对象用于设置或获取 <base> 元素的 href 属性。元素。

属性

以下是 Base 对象 − 的属性

属性描述
href设置或返回基础元素中 href 属性的值
target设置或返回基础元素中 target 属性的值

语法

以下是语法 −

创建基础元素 −

document.createElement ("base")

访问基础元素 −

var a = document.getElementById("demoBase");

示例

让我们看一个基础对象的示例 −

<!DOCTYPE html>
<html>
<body>
<p>Create the element first and then access it</p>
<p>Click the button below to create or access BASE element.</p>
<button onclick="CreateBase()">CREATE</button>
<button onclick="AcessBase()">ACCESS</button>
<p id="SAMPLE"></p>
<script>
   function CreateBase() {
      var x = document.createElement("BASE");
      x.setAttribute("id","myBase");
      x.setAttribute("href", "https://www.google.com");
      document.head.appendChild(x);
      document.getElementById("SAMPLE").innerHTML = "BASE element with href
      https://www.google.com is created";
   }
   function AcessBase() {
      var x = document.getElementById("myBase").href;
      document.getElementById("SAMPLE").innerHTML = x;
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

点击"创建" −

点击 ACCESS 按钮 −

在上面的例子中 −

我们创建了两个按钮 CREATE 和 ACCESS,分别用于执行 CreateBase() 和 AccessBase() 函数。

<button onclick="CreateBase()">CREATE</button>
<button onclick="AcessBase()">ACCESS</button>

CreateBase() 函数创建一个基元素并将其赋值给变量 x。然后使用 setAttribute() 方法设置其 id 和 href。之后,使用 appendChild() 属性将新创建的基元素附加到文档头。最后,基元素创建消息显示在与其关联的 id 为 SAMPLE 的段落中。

function CreateBase() {
   var x = document.createElement("BASE");
   x.setAttribute("id","myBase");
   x.setAttribute("href", "https://www.google.com");
   document.head.appendChild(x);
   document.getElementById("SAMPLE").innerHTML = "BASE element with href https://www.google.com is created";
}

我们创建了 AcessBase() 函数来访问我们新创建的 <base> 元素。该函数通过 id 获取元素,然后获取其 href 值并将其赋值给名为 x 的变量。x 中的信息随后会显示在 id 为 SAMPLE 的段落中。

function AcessBase() {
   var x = document.getElementById("myBase").href;
   document.getElementById("SAMPLE").innerHTML = x;
}

相关文章


有用资源