Artur
Artur

Reputation: 345

Parse HTML as a plain text via JavaScript

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:

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

htmlString.getElementById("someid").value

Upvotes: 5

Views: 11723

Answers (2)

eds1999
eds1999

Reputation: 1058

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

Upvotes: 16

Artur
Artur

Reputation: 345

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

Upvotes: -1

Related Questions