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

วิธีเปลี่ยนค่า HTML Attribute ด้วย JavaScript

เรียนรู้วิธีเปลี่ยนค่า HTML Element Attribute ด้วย JavaScript

สมมติคุณมี Anchor Element บนเว็บไซต์ ที่มี URL Link Path ผิดในแอตทริบิวต์ href

สถานที่พบบ่อยคือ Menu/Navigation Bar:

<nav> <ul> <li> <a href="/path-to-your-page" id="some-id">Link</a> </li> </ul> </nav>

สถานที่ทั่วไปอีกแห่งคือ Footer ล่างเว็บไซต์

สมมติมีข้อผิดพลาด href เป็น /contact-me แต่ควรเป็น /contact-us และไม่สามารถแก้ใน HTML โดยตรงได้ (อาจไม่มี Write Access Backend)

ต้องแก้ด่วนไม่ให้ผู้เยี่ยมชมเห็นหน้าว่างเวลาคลิก

หากมี Access Frontend Code เช่น ผ่าน CMS ใช้ JavaScript Override ค่า href เดิมบน Anchor Element โดยไม่ต้องแตะ Backend

จะแสดง 2 วิธี

Select Element ตาม ID

สมมติ HTML Markup เหมือนนี้ มี Unique ID ทุก Nav Link:

<nav> <ul> <li> <a href="/" id="home">Home</a> </li> <li> <a href="/services" id="services">Services</a> </li> <li> <a href="/contact-me" id="contact">Contact</a> </li> </ul> </nav>

ต้องการเปลี่ยน Href บน Contact Link

ก่อนอื่น Select Anchor/Link Element ตาม ID:

const contactLink = document.querySelector('#contact')

ใช้ Dot Notation เลือกแอตทริบิวต์ href ของ Anchor Element ให้ค่าใหม่ /contact-us:

contactLink.href = '/contact-us'

เสร็จแล้ว!

Log ใน Console จะเห็น Href Attribute เดิมที่ผิด ถูกแทนที่ด้วย URL Path ใหม่ที่ถูกต้อง:

console.log(contactLink.href) // output: "https://your-domain.com/contact-us"

โค้ด JS ทั้งหมด:

// Select anchor/link element based on its ID const contactLink = document.querySelector('#contact') // Change href value contactLink.href = '/contact-us' // Print result console.log(contactLink.href)

Select Element ตามค่า String เฉพาะ

อาจอยู่ในสถานการณ์ที่ Link Element ไม่มี Unique ID หรือ Class HTML Markup อาจแบบนี้:

<nav> <ul> <li> <a href="/">Home</a> </li> <li> <a href="/services">Services</a> </li> <li> <a href="/contact-me">Contact</a> </li> </ul> </nav>

ไม่เป็นไร ใช้ CSS3 Selector กับ querySelector() ระบุว่าต้องการ Select Exact String Value คือ /contact-me

วิธีทำ:

const contactLink = document.querySelector('a[href*="/contact-me"]')

Print Href Value จาก Variable ดูว่าเจอ Href ที่ต้องการไหม:

console.log(contactLink.href) // output: "https://your-domain.com/contact-me" 

เจอแล้ว!

ตอนนี้เปลี่ยน href ให้ถูกต้องเหมือนตัวอย่างก่อนหน้า:

contactLink.href = '/contact-us'

โค้ดทั้งหมด:

// Select link with specific href string value const contactLink = document.querySelector('a[href*="/contact-me"]') // Change href string value contactLink.href = '/contact-us' // Print result console.log(contactLink.href)