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
Sushil kumar
source share10 answers
Just try:
var title = $(html).filter('title').text(); +23
hsz
source shareJust 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
jAndy
source shareThis 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; +6
Loktar
source shareHow 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.
+4
adeneo
source shareIn 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
Saiid at RLTSquare
source share html.match(/<title>(.*)<\/title>/)[1] 0
griffon vulture
source shareObviously not recommended if you can use jQuery but for pure Javascript:
/<title>(.*)<\/title>/.exec(html)[1] 0
ach
source share html.substring(html.indexOf('<title>')+7, html.indexOf('</title>')) 0
Jalay
source shareYou 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
Ramsh
source shareYou can also try the following:
$('head > title').text(); 0
Fahim
source share