-1

I am trying to pull content inside a variable using plain java script. I am trying to get only part of the variable with an id. In this example I am trying to pull only part of html with id ‘container’.

My fiddle https://jsfiddle.net/a2ngc9jv/2/

var htmlPage = `
<html>
<div>
testing but not required
</div>
  <div id="container">
    <p>
     i want to pull this whole block from parent 
    </p>
    <p>
      test 2
    </p>
  </div>

</html>`;

console.log(htmlPage.getElementById("container"))
console.log(document.getElementById("container"))
Kurkula
  • 6,386
  • 27
  • 127
  • 202
  • That isn't going to work unless you convert `htmlPage` into a DOM element. –  Nov 15 '17 at 20:03
  • if you're HTML is just a javascript string, there is no such `getElementById` method you can call on it. Also, it's not clear what you mean by "pulling" a part. – ValLeNain Nov 15 '17 at 20:04
  • Are you trying to do this in the browser or in something like Node? – Mark Nov 15 '17 at 20:04
  • any other option to pull substring? – Kurkula Nov 15 '17 at 20:04
  • I am using a ajax call and it results html page. I am trying to cut only a block from that page. – Kurkula Nov 15 '17 at 20:05
  • Possible duplicate of [Converting HTML string into DOM elements?](https://stackoverflow.com/questions/3103962/converting-html-string-into-dom-elements) –  Nov 15 '17 at 20:07

2 Answers2

1

htmlPage is a string not a document node. However it's easy to put it into one:

var htmlPage = `
<html>
<div>
testing but not required
</div>
  <div id="container">
    <p>
     i want to pull this whole block from parent 
    </p>
    <p>
      test 2
    </p>
  </div>

</html>`;

// it might not be "allowed" to put a html tag inside a div but it works for this purpose.
var n = document.createElement('div');
n.innerHTML = htmlPage;

var content = n.querySelector('#container p:first-child').innerHTML;

console.log(content);
James
  • 20,957
  • 5
  • 26
  • 41
  • There's also `DOMParser`, as demonstrated [here](https://stackoverflow.com/questions/3103962) –  Nov 15 '17 at 20:06
1

If you're in the Browser you can use DOMparser() to turn this into a real dom object, then you can call the method you want to get elements from it.

var htmlPage = `
<html>
<div>
testing but not required
</div>
  <div id="container">
    <p>
     i want to pull this whole block from parent
    </p>
    <p>
      test 2
    </p>
  </div>

</html>`;


var parser=new DOMParser();
var htmlDoc=parser.parseFromString(htmlPage, "text/html");

console.log(htmlDoc.getElementById("container"))
console.log(htmlDoc.getElementById("container").innerHTML)
Kurkula
  • 6,386
  • 27
  • 127
  • 202
Mark
  • 90,562
  • 7
  • 108
  • 148