Aman
Aman

Reputation: 671

get the string enclosed in a tag in a string Jquery

I am trying to get data enclosed between tags in a string. I get a string in such format and I need to parse it to get only whats enclosed in tags.

var s = "Something something <details>Required data</details>";

I want to get the data that is enclosed between the <details> tag

I tried

alert($('s').find('details').text());

But its just blank output. Regular expressions would help but it seems to me that there maybe is a better way.

I would welcome any help.

Thank you.

Upvotes: 2

Views: 4233

Answers (2)

plalx
plalx

Reputation: 43718

If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with ). If not, the string is interpreted as a selector expression, as explained above.

It seems that jQuery is confused at your html string and treats it as a selector. When you want to explicitely parse html, you may need to use $.parseHTML.

var s = "Something something <details>Required data</details>",
    $s = $($.parseHTML(s)),
    text = $s.filter('details').text();

console.log(text); //Required data

You could also do something like:

$('<div>').html(s).find('details').text();

Upvotes: 4

Tats_innit
Tats_innit

Reputation: 34107

Demo 1.8.2 and above: http://jsfiddle.net/SSL2q/

Demo 1.7.2 and below : http://jsfiddle.net/FGpSP/

API:

old replies: Find element at HTML string or How to get an HTML element from a string with jQuery worth a read.

Hope rest fits your needs :)

Code

var s = "something sometihng <details> I want this </details>";

alert("abc");
alert($(s).filter('details').text());

Code

var s = "something sometihng <details> I want this </details>";

alert("abc");
alert($($.parseHTML(s)).filter('details').text());

Upvotes: 1

Related Questions