ceth
ceth

Reputation: 45295

Get title from HTML

I have a server side function which returns content of HTML page:

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup

    Meteor.methods({
      sayHello: function() {
        var response = Meteor.http.call("GET", "http://google.com");
        return response;
      }
    });
  });

And I have client code where I am trying to get title from this HTML page:

'click .add_tag' : function(e,t) { //Session.set('editing_tag_id', e.target.id);

  Meteor.call("sayHello", function(err, response) {
    var title = $(response.content).find("title").text();
    var title2 = $(response).find("title").text();
    var title3 = response.content.match(/<title[^>]*>([^<]+)<\/title>/)[1];
    alert(title3);
  });

I would like to get jQuery version ('title' or 'title2'), but it doesn't works. It returns empty string.

'Title3' - version works fine, but I don't like regexps. :)

Is there any way to make 'jQuery'-versions works ?

Upvotes: 0

Views: 184

Answers (3)

Craig
Craig

Reputation: 4399

As requested, I will reiterate my comment as an answer...

I would stick with the regex, even though you don't like it. There is a huge overhead of constructing a DOM element that is essentially an entire page, purely for the purpose of parsing a small amount of text. The regex is more lightweight and will perform adequately in slower browsers or on slower machines.

Upvotes: 1

Rebolon
Rebolon

Reputation: 1307

Don't forget one thing : you should never return HTML to client. You should return Json (or even Xml) that your client will transform into Html using Template. You are doing like a lot of dev doing Bad Ajax.

Don't forget : "only data on wire, not display".

So there should not be any problem coz, on response you just have to take data from Json formatted response and inject it inside your Template.

Upvotes: 0

scrappedcola
scrappedcola

Reputation: 10572

Wrap response.content in a <div> and then do a selection off of that. This way you have a proper structure to start from rather than an array that you might actually be getting.

var $wrap = $("<div></div>").html(response.content);
$wrap.find("title").text();

An example of what is probably going on: http://jsfiddle.net/UFtJV/

Upvotes: 0

Related Questions