views:

110

answers:

2

I have a string of html text stored in a variable:

var msg = '<div class="title">Alert</div><div class="message">New user just joined</div>'

I would like to know how I can filter out "New user just joined" from the above variable in jQuery/Javascript so that I can set the document title to just the message.

Thank you.

+5  A: 

Like this:

document.title = $(msg).filter("div.message").text();

Note that if the message changes to be wrapped in an element, you'll need to replace filter with children.

EDIT: It looks like the div that you want is nested in other element(s).
If so, you can do it like this:

document.title = $("div.message", msg).text();

Explanation: $('<div>a</div><div>b</div>') creates a jQuery object holding two different <div> elements. You can find the one you're looking for by calling the filter function, which finds mathcing elements that are in the jQuery object that you call it on. (Not their children)

$('<p><div>a</div><div>b</div><p>') creates a jQuery object holding a single <p> element, and that <p> element contains two <div> elements as children. Calling $('selector', 'html') will find all descendants of the elements in the HTML that match the selector. (But it won't return the root element(s))

SLaks
Please edit that into your question.
SLaks
My apologies. I replaced it with filter and it works perfectly. Thank you.
ensnare
A: 

This is a hack and not very clean, but it should work:

  1. add a div node and set its html to your text message,
  2. get the text of the added element and store it in a variable
  3. destroy the node
  4. set the title with the contents of the variable in step 2
Majid