get h1 text javascript

How to Get H1 Text Using JavaScript

Getting the text of an H1 element using JavaScript can be quite easy. Here are two methods:

Method 1: Using the innerHTML Property


const h1Text = document.querySelector('h1').innerHTML;
console.log(h1Text);

This code creates a variable called h1Text and sets its value to the innerHTML of the first H1 element in the document. The querySelector() method is used to select the H1 element by its tag name. The text is then logged to the console using the console.log() method.

Method 2: Using the textContent Property


const h1Element = document.querySelector('h1');
const h1Text = h1Element.textContent;
console.log(h1Text);

This code creates a variable called h1Element and sets its value to the first H1 element in the document using the querySelector() method. The textContent property is then used to get the text content of the H1 element. Finally, the text is logged to the console using the console.log() method.

Putting It in HTML Div

Method 1


  const h1Text = document.querySelector('h1').innerHTML;
  console.log(h1Text);
  

Method 2


  const h1Element = document.querySelector('h1');
  const h1Text = h1Element.textContent;
  console.log(h1Text);
  

Using Highlight.js for Syntax Highlighting

Highlight.js is a popular library for syntax highlighting in web applications. Here's how to use it with our code:


<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.1.0/styles/default.min.css">
  <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.1.0/highlight.min.js"></script>
  <script>hljs.initHighlightingOnLoad();</script>
</head>
<body>
  <div>
    <h3>Method 1</h3>
    <pre><code class="javascript">
    const h1Text = document.querySelector('h1').innerHTML;
    console.log(h1Text);
    </code></pre>
  </div>

  <div>
    <h3>Method 2</h3>
    <pre><code class="javascript">
    const h1Element = document.querySelector('h1');
    const h1Text = h1Element.textContent;
    console.log(h1Text);
    </code></pre>
  </div>
</body>
</html>

In this code, we have added the Highlight.js CSS and JavaScript files to the <head> section of our HTML. We have also added a script to initialize syntax highlighting on page load using the hljs.initHighlightingOnLoad() method. Finally, we have wrapped our code examples with <pre> and <code> tags and added the appropriate language class for syntax highlighting.

With Highlight.js, our code examples now look much better and are easier to read.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe