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

การดึง innerText ของ h1 โดยไม่รวม child element ใน JavaScript

คำอธิบาย

ใช้ childNodes[0].textContent เพื่อดึงข้อความตรงของ h1 โดยไม่รวมข้อความใน child element (เช่น <span>)

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

<h1> This is h1 tag........<span>This is span tag inside h1 tag.......... </span></h1>

<script>
var valueOfh1 = document.querySelector('div.second-header h1');
var value = valueOfh1.childNodes[0].textContent;
console.log(value);
</script>

ผลลัพธ์

แสดงเฉพาะ "This is h1 tag........" ไม่รวมข้อความใน span