May 1, 2012

get the title from a context

Question by Hermione

How Do I select the title of the context? I am suppose to select it to change the title of the page.

var handler = function(context){
    document.title = //context's title
    ....
}

//sample context from ajax request
var context = '<!DOCTYPE html><html>
            <head><title>Hello</title></head>
            <body>
            <a href="#">Click Here</a><p>This is my sentence.</p>
            </body></html>';

.ajax{(
    ...
    success: function(data){
                 handler(data);
             }
});

EDIT: I forgot the doctype just incase it’s necessary. The context was from an AJAX Request.

Answer by Starx

You can use regex to extract the title as well

var matches = context.match(/<title>(.*?)</title>/);
var title = matches[1];

Demo


Just discovered a way to do this, the non-regex way

title = $(context).filter("title");
console.log(title.html());

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!