开发者

Get div value from a string

I have the following string

str ='<div id="example">Text</div><div id="test">Test</div>';

how can I get the example and test content with jQu开发者_高级运维ery.


You need to convert the text to a jQuery object and then use standard traversing methods

str ='<div id="example">Text</div><div id="test">Test</div>';
var live_str = $('<div>',{html:str});

var example = live_str.find('#example').text();
// example variable now holds 'Text'

var test = live_str.find('#test').text();
// example variable now holds 'Test'

demo at http://jsfiddle.net/gaby/FJSm6/


As you see i set the string as the html of another element, because otherwise the divs would be at the top level and you would not be able to traverse them with .find()..


You can always create min-DOMs (if you wish) by passing a valid HTML to jQuery:

$(str).wrap('<p>').parent().find('div').text();

so:

var textContent = $(str).wrap('<p>').parent().find('#example').text();
var testContent = $(str).wrap('<p>').parent().find('#test').text();


The easiest would be to store the content in a var and work with that:

var example = $('#example').text(), test = $('#test').val();

You can also get the contents using .html() if you would like to also grab the html tags if necessary.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜