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
Getting an HTML H1 value to JavaScript variable?
To get the value of an HTML H1 element into a JavaScript variable, you can use document.getElementById().innerHTML to access the text content inside the heading.
Basic Syntax
var headingText = document.getElementById('elementId').innerHTML;
Example: Getting H1 Content
Let's say we have the following H1 heading with an id:
<h1 id="demo">This is the demo program of JavaScript</h1>
Here's how to get the H1 value using JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Getting H1 Value</title>
</head>
<body>
<h1 id="demo">This is the demo program of JavaScript</h1>
<script>
var data = document.getElementById('demo').innerHTML;
console.log("The H1 content is: " + data);
// Display in an alert box
alert("H1 text: " + data);
</script>
</body>
</html>
Output
The H1 content is: This is the demo program of JavaScript
Alternative Methods
You can also use other methods to get the H1 content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>H1 Methods Comparison</title>
</head>
<body>
<h1 id="myHeading">Welcome to <strong>JavaScript</strong> Tutorial</h1>
<script>
var element = document.getElementById('myHeading');
// Method 1: innerHTML (includes HTML tags)
var withTags = element.innerHTML;
console.log("innerHTML: " + withTags);
// Method 2: textContent (plain text only)
var textOnly = element.textContent;
console.log("textContent: " + textOnly);
// Method 3: innerText (plain text, respects styling)
var innerText = element.innerText;
console.log("innerText: " + innerText);
</script>
</body>
</html>
Output
innerHTML: Welcome to <strong>JavaScript</strong> Tutorial textContent: Welcome to JavaScript Tutorial innerText: Welcome to JavaScript Tutorial
Method Comparison
| Method | Returns HTML Tags? | Best For |
|---|---|---|
innerHTML |
Yes | Getting full HTML content |
textContent |
No | Getting plain text only |
innerText |
No | Text as displayed to user |
Conclusion
Use innerHTML to get the full HTML content of an H1 element, or textContent for plain text only. Both methods require the element to have an id attribute for easy selection.
Advertisements
