0

Suppose I have a DOMString which is of kind

"<!DOCTYPE html><html><div id="d1"><p>foo</p></div></html>"

and I want to store the paragraph content in a variable (say, pContent), such that

pContent == "foo"

What do you suggest me? I can use only javascript-code (and libraries entirely written in .js if needed).

Giuseppe Crinò
  • 457
  • 3
  • 14

2 Answers2

2

Well, since you mentioned the use of libraries, you can pass the contents of your string to jQuery and extract the tree. For example:

var myString = '<!DOCTYPE html><html><div id="d1"><p>foo</p></div></html>',
    $myString = $(myString),
    para = $myString.find('p').text();

Your variable para now contains the string foo.

BenM
  • 51,470
  • 24
  • 115
  • 164
0

Using plain JS:

var str = '<!DOCTYPE html><html><div id="d1"><p>foo</p></div></html>';

var htmlWrapper = document.createElement('html');
htmlWrapper.innerHTML = str;
var pNodes = htmlWrapper.getElementsByTagName('p');

pContent = pNodes[0].innerText || pNodes[0].textContent;

JSFiddle

Although, JQuery would be a better solution but adds a lot of functionality you may not need.

Preston S
  • 2,682
  • 23
  • 36