Extract the value of the to a variable using JavaScript?

To extract the value of the <text> element to a variable using JavaScript, use the textContent property to get the text content from any HTML or SVG text element.

Syntax

var textValue = document.getElementById("elementId").textContent;

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Extract SVG Text Value</title>
</head>
<body>
    <svg width="300" height="150">
        <text id="myText" x="50" y="80" font-size="16" fill="blue">
            This is the JavaScript Tutorial
        </text>
    </svg>
    
    <script>
        var originalText = document.getElementById("myText").textContent;
        console.log("Extracted text:", originalText);
        
        // You can also store it in another variable
        var myVariable = originalText.trim();
        console.log("Trimmed text:", myVariable);
    </script>
</body>
</html>

Output

Extracted text:             This is the JavaScript Tutorial
        
Trimmed text: This is the JavaScript Tutorial

Working with Different Text Elements

The same technique works with regular HTML text elements:

<!DOCTYPE html>
<html>
<body>
    <p id="paragraph">Hello from paragraph</p>
    <h2 id="heading">Sample Heading</h2>
    <span id="span">Span text content</span>
    
    <script>
        // Extract from different elements
        var paragraphText = document.getElementById("paragraph").textContent;
        var headingText = document.getElementById("heading").textContent;
        var spanText = document.getElementById("span").textContent;
        
        console.log("Paragraph:", paragraphText);
        console.log("Heading:", headingText);
        console.log("Span:", spanText);
    </script>
</body>
</html>

Key Points

  • Use textContent to get plain text without HTML tags
  • Use innerHTML if you need to preserve HTML markup
  • Always ensure the element exists before accessing its properties
  • Use trim() to remove extra whitespace if needed

Conclusion

Extracting text content to variables is straightforward using document.getElementById().textContent. This method works consistently across HTML and SVG text elements, making it essential for dynamic content manipulation.

Updated on: 2026-03-15T23:18:59+05:30

798 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements