ออบเจ็กต์ HTML DOM Base เชื่อมโยงกับองค์ประกอบ HTML
คุณสมบัติ
ต่อไปนี้เป็นคุณสมบัติของวัตถุฐาน -
| คุณสมบัติ | คำอธิบาย |
|---|---|
| href | ตั้งค่าหรือคืนค่าของแอตทริบิวต์ href ในองค์ประกอบพื้นฐาน |
| เป้าหมาย | ตั้งค่าหรือคืนค่าของแอตทริบิวต์เป้าหมายในองค์ประกอบฐาน |
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์สำหรับ −
การสร้างองค์ประกอบพื้นฐาน -
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() ถูกสร้างขึ้นเพื่อเข้าถึงองค์ประกอบ
function AcessBase() {
var x = document.getElementById("myBase").href;
document.getElementById("SAMPLE").innerHTML = x;
}