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

innerHTML vs innerText ใน JavaScript - ความแตกต่างและการใช้งาน

ทั้ง innerHTML และ innerText ใช้สำหรับอ่าน/เขียนเนื้อหาภายใน Element แต่ทำงานต่างกันอย่างสิ้นเชิง

ความแตกต่างหลัก

คุณสมบัติinnerHTMLinnerText
คืนค่าHTML String (รวม Tags)Plain Text (ข้อความบริสุทธิ์)
RenderingParse และ Render HTMLแสดงข้อความตามตัวอักษร
Spacing/Line breaksเก็บตาม HTML จริงคำนึงถึง CSS Layout (visible text)
Security (XSS)⚠️ อันตราย ถ้าใส่ User Input✅ ปลอดภัย (Escape อัตโนมัติ)
Performanceช้ากว่า (Parse HTML)เร็วกว่า

ตัวอย่างเปรียบเทียบ

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>innerHTML vs innerText</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
        .sample { 
            background: #f0f0f0; 
            padding: 15px; 
            margin: 10px 0; 
            border: 1px solid #ddd; 
        }
        .result { 
            font-size: 16px; 
            font-weight: 500; 
            margin: 10px 0; 
            padding: 10px; 
            background: #f8f9fa; 
            border-left: 3px solid #667eea;
            white-space: pre-wrap;
            font-family: monospace;
        }
        button { padding: 8px 16px; margin: 10px 0; cursor: pointer; }
    </style>
</head>
<body>
    <h1>innerHTML vs innerText</h1>
    <div class="sample" id="sample">Hello <b>World</b> <i>Some Text</i></div>
    <div class="result" id="htmlResult">innerHTML:</div>
    <div class="result" id="textResult">innerText:</div>
    <button class="Btn" id="compareBtn">เปรียบเทียบ</button>
    <h3>กดปุ่มเพื่อดูผลลัพธ์ของ innerHTML และ innerText</h3>

    <script>
        const sampleEle = document.getElementById("sample");
        const htmlResult = document.getElementById("htmlResult");
        const textResult = document.getElementById("textResult");
        const btn = document.getElementById("compareBtn");
        
        btn.addEventListener("click", () => {
            htmlResult.innerHTML = "innerHTML:
" + escapeHtml(sampleEle.innerHTML); textResult.innerHTML = "innerText:
" + escapeHtml(sampleEle.innerText); }); function escapeHtml(text) { const div = document.createElement("div"); div.textContent = text; return div.innerHTML; } </script> </body> </html>

ผลลัพธ์

Element: Hello World Some Text

Propertyผลลัพธ์
innerHTMLHello <b>World</b> <i>Some Text</i> (รวม Tags)
innerTextHello World Some Text (เฉพาะข้อความ, รวม Spacing)

textContent: ตัวเลือกที่ 3 (แนะนำสำหรับข้อความบริสุทธิ์)

คุณสมบัติinnerTexttextContent
คำนึงถึง CSS✅ ใช่ (ซ่อน display:none)❌ ไม่ (อ่านทั้งหมด)
Performanceช้ากว่า (ต้องคำนวณ Layout)เร็วกว่า
Line Breaksตาม Visual Renderingตาม DOM Structure
StandardNon-standard (แต่ทุก Browser รองรับ)✅ Standard

เมื่อไหร่ควรใช้อะไร?

✅ ใช้ innerHTML เมื่อ:

  • ต้องการ Insert HTML Structure ใหม่ทั้งชุด
  • Template Rendering (แต่ควรใช้ Template Literals + DOM API แทน)
  • Clone HTML Content

✅ ใช้ textContent เมื่อ:

  • อ่าน/เขียนข้อความบริสุทธิ์ (แนะนำส่วนใหญ่)
  • Performance สำคัญ
  • ป้องกัน XSS (Escape อัตโนมัติ)

✅ ใช้ innerText เมื่อ:

  • ต้องการข้อความที่ "ผู้ใช้มองเห็น" (คำนึง CSS)
  • Copy Text ให้ User (Clipboard)

⚠️ คำเตือนความปลอดภัย (XSS)

// ❌ อันตราย - User Input ตรงไป innerHTML
element.innerHTML = userInput; // ถ้า userInput = "innerHTML vs innerText ใน JavaScript - ความแตกต่างและการใช้งาน"

// ✅ ปลอดภัย - ใช้ textContent
element.textContent = userInput; // แสดงเป็นข้อความ "innerHTML vs innerText ใน JavaScript - ความแตกต่างและการใช้งาน"

// ✅ ปลอดภัย - Sanitize ก่อน (DOMPurify หรือ Custom)
element.innerHTML = DOMPurify.sanitize(userInput);

สรุป

  • textContent = Default choice สำหรับข้อความ (Fast, Safe, Standard)
  • innerText = เมื่อต้องการข้อความที่ "มองเห็น" (CSS-aware)
  • innerHTML = เมื่อต้องจัดการ HTML Structure (ระวัง XSS!)