开发者

How to grab some data from returned html in jquery

开发者 https://www.devze.com 2023-03-16 22:47 出处:网络
Suppose i got returned some html in variable data. In that variable i have <h1> Title </h1>

Suppose i got returned some html in variable data. In that variable i have

<h1> Title </h1>

Now i want t开发者_高级运维o grab that text Title and remove <h1> Title </h1> from variable data

how can i achieve that in jquery


You could do $.parseXML() to convert the string to an XML document and then run DOM manipulation using jQuery

var XML= $.parseXML(data);
var title = $(XML).find('h1').text(); //Get the text inside h1 tags.
$(XML).find('h1').remove(); // Remove the h1 tags 

http://jsfiddle.net/QNnLe/


You can wrap the contents into a dummy element, get that element and then use find to find the content you are looking for:

var data = "<h1> Title </h1>";    
console.log($(data).wrap('<div />').parent().find('h1 ').text()); // Title

var data = "sssssss  <h1> Title </h1> aaaaaaaaaa";    
console.log($(data).wrap('<div />').parent().find('h1').text()); //Title

The wrapping is useful if the data isn't perhaps wrapped inside an element already.

example: http://jsfiddle.net/niklasvh/VWnVj/


Something like this:

var title = $(data).text();


Or like this:

data = data.replace(/<\/?[^>]+>/gi, '');
0

精彩评论

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

关注公众号