How do take HTML recieved over ajax and connect it to the DOM?

This is an excerpt from my ajax function

      parser = new DOMParser();
      xmlDoc = parser.parseFromString(ajax.responseText,"application/xml");
      document.getElementById(div).innerHTML = xmlDoc;

The above doesn’t throw any errors in the console but it doesn’t display anything either. And when I try to view the div I’m updating in the insepector it’s completely empty. Am I misunderstanding something here?

This system was almost working when I was just setting the innerHTML of that div to ajax.responseText. The newly recieved HTML would display as expected, but some functions loaded on the initial page hit seemed to have troubles accessing the newly recieved form elements that sometimes come in with the HTML. So I figured this new HTML isn’t being connected to the existing DOM, ergo, I ended up here.

Am I on the right path here? My goal is to be able to access the form elements that come in with the ajax response.

Hi @wh33t1! If you just want to set the .innerHTML, you must not parse the response to a document first – that will be done automatically:

myElement.innerHTML = '<div>foo</div>'

The DOMParser is useful where you want to process that HTML in a certain way, such as extract certain elements. For example, if your ajax.responseText contains an entire HTML page like

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <img src="path/to/image" alt="Batman">
  <script src="main.js"></script>
</body>
</html>

but you are only interested in the image, you might do something like

const parser = new DOMParser()
const doc = parser.parseFromString(ajax.responseText, 'text/html')
const img = doc.querySelector('img')

if (img) {
  myElement.appendChild(img)
}
1 Like

Hi thanks for the response!

in the ajax.responseText I have 6 input checkboxes in them. I cannot seem to access these via document.getElementById(‘chkbox1’) for example.

Do I need to parse the responseText to make that possible?

Yes, the response text is always a string, which you can’t query like a document; you’ll have to parse it first. Then you can insert some given nodes with .appendChild() (not as .innerHTML).

1 Like

Ahh ok. I thought so.

So before I make an attempt on this could you critique my methods here?

I take the responseText and I parse with DOMParser.

That will give me an object correct?

Then I can just take the first node in the object (in this case it’s a div containing everything) and I can just replace the existing child in the DOM with the one I’ve just parsed?

Aye, just note that the first node will be the html element, so you’ll have to use .querySelector() or similar to get the element you need.

1 Like

Awesome! Thanks so much! I’ll report back if I have further issues.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.