My First...">

How to get title tag using jQuery?

I have html in string form.

var html = " <html> <head> <title> Some Text </title> </head> <body> <h1> My First Heading </h1> <p> My first paragraph. </p> </body> </html> "; 

It has a title tag. How to get text inside title tag using jquery or javascript?

+7
javascript jquery
source share
10 answers

Just try:

 var title = $(html).filter('title').text(); 
+23
source share

Just because no one has mentioned this yet, you can also use document.implementation.createHTMLDocument() for this purpose.

 var domstr = "<html><head><title>Some Text</title></head><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>"; doc = document.implementation.createHTMLDocument('1337'); doc.documentElement.innerHTML = domstr; alert( doc.title ); 
+7
source share

This is my crack. Create a documentFragment, add an element to it and use querySelector to get the element, and then textContent to get the text.

 var html = "<html><head><title>Some Text</title></head><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>", docFrag = document.createDocumentFragment(), el = document.createElement('html'); el.innerHTML = html; docFrag.appendChild(el); var text = docFrag.querySelector('title').textContent; 

Live demo

+6
source share

How about using DOMparser

 var html = "<html><head><title>Some Text</title></head><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>", doc = (new DOMParser()).parseFromString(html, 'text/html'); title = doc.title; 

Note. . This is not supported in any version of Safari.

Fiddle

+4
source share

In javascript just

 document.title 

Code example

 <html> <head> <title>My Page Title</title> </head> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = document.title; </script> </body> </html> 
+3
source share
 html.match(/<title>(.*)<\/title>/)[1] 
0
source share

Obviously not recommended if you can use jQuery but for pure Javascript:

 /<title>(.*)<\/title>/.exec(html)[1] 
0
source share
 html.substring(html.indexOf('<title>')+7, html.indexOf('</title>')) 
0
source share

You can get this text using this jQuery selector.

 $(function(){ var html = "<html><head><title>Some Text</title></head><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>"; var titleHTML = $(html).find("title").html(); alert(titleHTML); }); 

He will warn "Some Text"

0
source share

You can also try the following:

 $('head > title').text(); 
0
source share

All Articles