开发者

Parse string for text between divs

开发者 https://www.devze.com 2022-12-18 12:11 出处:网络
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 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 vari开发者_JS百科able in jQuery/Javascript so that I can set the document title to just the message.


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))


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
0

精彩评论

暂无评论...
验证码 换一张
取 消