JavaScript - Get the text of a span element


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

Example

 Live Demo

<!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>

Output

On clicking the “CLICK HERE” button −


Updated on: 11-May-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements