开发者

Parse a string containing html using JQuery

开发者 https://www.devze.com 2023-01-08 14:45 出处:网络
Astounded this question didn\'t show up in the related questions list. There\'s some similar stuff, but I\'d like to know:

Astounded this question didn't show up in the related questions list. There's some similar stuff, but I'd like to know:

string s = "<p>Cats</p><div id='fishbiscuits'>myValue</div>";

I want to use JQuery开发者_如何学Python to get myValue.

How can I do this?


Use the jQuery function to create the objects and then you can use it like you would any other collection of elements. Any of these should work just fine:

// Using filter()
$(s).filter("#fishbiscuits").text();

// Wrapping with a div and using find()
$('<div>' + s + '</div>').find("#fishbiscuits").text();

// Wrapping with a div and using selector context
$('#fishbiscuits', '<div>' + s + '</div>').text();

// Creating a div, setting the html and then using find
$('<div>').html(s).find("#fishbiscuits").text();


Based on the info provided, this should do the trick:

var s = "<p>Cats</p><div id='fishbiscuits'>myValue</div>";
var dummyElement = $( '<div>' + s + '</div>' );
var yourString = $( '#fishbiscuits', dummyElement ).html ();

It basicly creats a new DOM element containing the HTML in your string, then searches for the element with the id 'fishbiscuits' and returns it's inner HTML

0

精彩评论

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