JavaScript - 获取 span 元素的文本
若要在 JavaScript 中获取 span 元素文本,可使用以下代码:
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample { font-size: 18px; font-weight: 500; } </style> </head> <body> <h1>JavaScript Date Methods</h1> <span class="test">This is some sample text inside a span element</span> <div class="sample"></div> <button class="Btn">CLICK HERE</button> <h3> Click on the above button to get the span text </h3> <script> let sampleEle = document.querySelector(".sample"); let spanEle = document.querySelector(".test"); document.querySelector(".Btn").addEventListener("click", () => { sampleEle.innerHTML = "The span text is = " + spanEle.innerHTML; }); </script> </body> </html>
输出
单击“点击此处”按钮后:
广告