Reputation: 2631
I have a whole html document in a variable but I don't know how to get the title. Tryied the code below but it only works for specific divs and I don't know why.
//valid html
var data='<!DOCTYPE html><html><head><meta charset="UTF-8" /><title>MyTitle</title><meta name="description" content="MyDEsc" /></head><body><div id="header">header content</div><div class="container" id="wrapper">Default body<div id="home">home</div><div id="project"><div>content</div><div>content</div><div>content</div></div></div></body></html>'
console.log($(data).find('title').text()) //nothing
console.log($('title', $(data)).text()) //nothing
console.log('header :' + $('#header', $(data)).html()) //undefined
console.log('header :' + $('#home', $(data)).html()) //expected value
console.log('project :' + $('#project', $(data)).html()) //expected value
Demo here: http://jsfiddle.net/22RLk/
Upvotes: 1
Views: 163
Reputation: 97672
Your html, head, and body tags are stripped out so what you end up with is a collection of elements rather than a full document. The title is one of those elements.
console.log($(data).filter('title').text())
If you want to create a document you can use
document.implementation.createHTMLDocument(data)
create a javascript document Object
How to create Document objects with JavaScript
Upvotes: 4
Reputation: 1249
Pure Javascript:
console.log('title :' + data.substr(data.indexOf('<title>') + 7,data.indexOf('</title>')-7-data.indexOf('<title>')));
Upvotes: 1
Reputation: 968
$(document).find('title').text()
$(document).find('title').html()
Try that way
Upvotes: 0
Reputation: 3079
I would use Regexp for this, like here: http://jsfiddle.net/maximgladkov/6TTF5/1/
console.log(data.match(/<title>(.+?)<\/title>/)[1])
Upvotes: 2