Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

สร้าง HTML Document พร้อม Custom URL ใน JavaScript

ใช้ document.implementation.createHTMLDocument() และ Element <base>

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const htmlDocument = document.implementation.createHTMLDocument();
        const customURL = htmlDocument.createElement('base');
        customURL.href = "https://www.tutorialspoint.com/java/index.htm";
        htmlDocument.head.append(customURL);
        console.log("Base URL=" + customURL.href);

        const modifiedURL = htmlDocument.createElement("a");
        modifiedURL.href = "../java/java_questions_answers.html";
        htmlDocument.body.append(modifiedURL);
        console.log("After Modifying URL=" + modifiedURL.href);
    </script>
</body>
</html>

วิธีรันโปรแกรม

  1. บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
  2. คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor

ผลลัพธ์ (Console)

Base URL=https://www.tutorialspoint.com/java/index.htm
After Modifying URL=https://www.tutorialspoint.com/java/java_questions_answers.html