Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
textContentto get plain text without HTML tags - Use
innerHTMLif 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.
Advertisements
