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

แทนที่เนื้อหาใน Div ด้วยข้อความจาก Element อื่นใน JavaScript

ใช้ querySelectorAll() หา Span ทั้งหมด แล้วเซต textContent จาก Element ต้นทาง

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

<!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>
    <h2 class="uniqueId"> My Name is John </h2>
    <div class="my-main-div-class">
        <div class="div-class-2">
            <span>My h6 value must be here...</span>
        </div>
        <div class="div-class-end">
            <span>My h6 value must be here...</span>
            <span>My h6 value must be here...</span>
        </div>
    </div>

    <script>
        const allSpan = document.querySelectorAll('.my-main-div-class span');
        const replaceAboveText = document.getElementsByClassName('uniqueId')[0].textContent;

        for (var newElement of allSpan) {
            newElement.textContent = replaceAboveText;
        }
    </script>
</body>
</html>

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

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

ผลลัพธ์

ทุก Span ใน .my-main-div-class จะแสดงข้อความ "My Name is John"