JavaScript - Get the text of a span element

JavascriptWeb DevelopmentObject Oriented Programming

To get the text of the span element in JavaScript, the code is as follows −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .sample {
      font-size: 18px;
      font-weight: 500;
<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>
Click on the above button to get the span text
   let sampleEle = document.querySelector(".sample");
   let spanEle = document.querySelector(".test");
   document.querySelector(".Btn").addEventListener("click", () => {
      sampleEle.innerHTML = "The span text is = " + spanEle.innerHTML;


On clicking the “CLICK HERE” button −

Updated on 11-May-2020 12:16:05