JavaScript Code to Get the Page Title

CK CK 3788 
Created at  
341 0 0

To extract the title of an HTML page from a given HTML string using JavaScript, you can parse the HTML and retrieve the content of the <title> tag. Here's how to do it:

The DOMParser in JavaScript is a web API used to parse an XML or HTML string into a DOM (Document Object Model) document. It enables developers to convert text-based markup (like HTML or XML) into an in-memory document object that can be navigated and manipulated using standard DOM methods.

JavaScript Code to Get the Page Title:

function getTitleFromHtml(html) {
  // Create a DOM parser to parse the HTML string
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  
  // Retrieve the content of the <title> tag
  const title = doc.querySelector('title');
  
  // Return the text content of the title, or null if not found
  return title ? title.textContent : null;
}

// Example HTML input (replace with your HTML content)
const htmlText = `
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Example Page Title</title>
</head>
<body>
  <h1>Hello, World!</h1>
</body>
</html>
`;

// Extract the page title
const pageTitle = getTitleFromHtml(htmlText);
console.log(pageTitle); // Outputs: "Example Page Title"

Explanation:

  1. DOMParser: Converts the HTML string into a DOM object.
  2. querySelector: Looks for the <title> tag in the HTML.
  3. textContent: Extracts the text content of the <title> tag.

If the <title> tag is not found in the HTML, the function will return null.

Tags DOMParser HTML Title Facebook X
Comments 0
Similar posts
  1. Javascript function to convert sitemap.xml to array
    603
  1. Making HTML Tables Responsive on Mobile: Addressing Text Overflow
    783
  2. How do we make better SEO with schema.org?
    428
  3. A Javascript code that returns Monthly Mortgage Payment and Tax
    1,266
  4. A simple JavaScript snippet to copy a string to the clipboard
    1,058
  5. Dynamic JSON Editor based in HTML/JavaScript
    514
  6. How to post content (image or video) to Instagram using the Instagram Graph API
    6,412
  7. Font name correctly having the same width space
    1,229
  8. JavaScript Algorithms
    722
  9. GraphQL Tutorial on CentOS 7: From Installation to Deployment
    564
  10. Capture all browser console logs including errors for debugging
    2,192
  11. Simple asynchronous/synchronous $.ajax() example using jQuery to make an HTTP GET request
    863
  12. JavaScript Code to Get Page Keywords
    353
  13. What is OpenGraph?
    367
  14. What is Twitter Cards?
    405
  15. Code to Extract the Site Thumbnail Image for Twitter or Facebook
    396
  16. JavaScript Code to Get Meta Description from HTML
    398
  17. Javascript code to extract favicon URL
    405
  18. RSS to Array in JavaScript
    2,169
  19. Understanding Elasticsearch from Installation to Trouble Shooting
    915
  20. IndexNow for better SEO
    321
  21. Enhancing SEO for Single Page Applications: Implementing Dynamic URL Updates
    1,043
  22. Method to ignore JavaScript Errors globally instead of try... catch for each of cases
    973
  23. Method to catch the browser console log and errors for remote web debugging
    2,191
  24. Atlassian Jira Ticket API Response Example
    2,807
  25. Three different type of Word-Wrap options in HTML CSS
    1,189
  26. JavaScript code to load XML Document
    604
  27. Creating a Pinterest-Style Card Layout with Bootstrap and Masonry
    599
  28. Equal Height Blocks in Bootstrap with JavaScript
    713
  29. Copy text to clipboard in Javascript
    1,717
  30. To block copy & paste on your blog content
    905
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,255
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    105
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    108
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    117
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    230
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233