6

I am making some ajax request that returns the whole HTML page as the response. I need to grab some data from that page, in particular, value of specific <input>.

What is the best way to do that?

My ideas:

  • Find where the <body> tag ends and </body> starts, grab all stuff inside to string, and put via innerHTML to some container.
  • Self-made parser: find the character position of the id I need, convert response string to an array, set position of reading equals position of id character, shift to where " character starts, read to buffer until new " come.

It would be perfect if there is a framework that uses classic DOM syntax to do that, like:

htmlString.getElementById("someid").value
2
  • "What is the best way..." ask for a (most likely) opinion-based answer which is off-topic for SO. "It would be perfect if there is a framework..." asks for an external resource which is also off-topic for SO. Commented Sep 13, 2020 at 10:13
  • @Andreas the best way (obviously) means the fastest, the easiest to use. It is not subjective, because we can count how many steps one should do, how much time it cost to run it. Commented Sep 13, 2020 at 10:46

2 Answers 2

18

A pretty elegant solution is to use DOMParser.

const parser = new DOMParser()
const virtualDoc = parser.parseFromString(htmlString, 'text/html')

Then, treat virtualDoc like you'd treat any DOM-element,

virtualDoc.getElementById('someid').value
Sign up to request clarification or add additional context in comments.

1 Comment

There's a typo in your code: virtualDom should be virtualDoc.
-1

Don’t know how good is it, but just passing the whole response with <html> and others tags to some container works. Then, one needs just to call

document.getElementById("needid").value

1 Comment

Is this an answer? If so, then please make it a good answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.