ใช้ 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>
วิธีรันโปรแกรม
- บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
- คลิกขวาที่ไฟล์ เลือก "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