Anonymous
Anonymous

Reputation: 1883

Ajax response as DOM object

Is there a way to get a response from the typical ajax function so that it can be dissected with getElements? I've tried query.responseText.getElementById but it works just as bad as it looks. You should be able to tell what I'm trying to achieve by seeing that snippet, though. I just need to get elements from an ajax response the same way as I would a normal DOM object.

Also, please do not suggest using jQuery. I use it when I have a lot of script and can use a lot of its functions, but in this case I only have a short script and a library 70x the size of it would seem like a waste.

Upvotes: 4

Views: 4462

Answers (5)

Gigoland
Gigoland

Reputation: 1453

For example javaScript "append" need parsed html (.body.firstElementChild get element only without body)

let parsedHtmlElement = new DOMParser().parseFromString(ajaxResultStringHtml, 'text/html').body.firstElementChild;
document.getElementById('js-my-terget-element').append(parsedHtmlElement);

Upvotes: 0

Alex Parloti
Alex Parloti

Reputation: 734

Parsing an SVG or HTML document

parser = new DOMParser();
doc = parser.parseFromString(stringContainingHTMLSource, "text/html");

doc will be a valid html document.

Upvotes: 5

Cody
Cody

Reputation: 10015

If your response is TEXT, I've seen ppl use ...xhr.responseText.spit('html>...body>...div id="yourTargetsParent">')[1].split('/div>.../body>.../html>')[0]; //just split the string up however!

Another way is to use iframe.contentWindow.document.body... (or contentDocument for some browsers)... just hide the iframe ya know.

Obviously, if you have control over the target that totally changes things (and this post probably wouldn't be here), but I've also seen some mean work arounds with the target's use of scripting its host dom, localStorage, splits/joins, webSQLDatabases, ...for string manipulation.

Honestly, I used to use a hidden div(thank you asleepysamurai!), but I thought I came across a more getElementById/jQuery.load type way. ..I'll post back if I find it...

Upvotes: 1

asleepysamurai
asleepysamurai

Reputation: 1372

Well you could have a hidden div on your page and set it's innerHTML to the Ajax response you receive. You could then call div.getElementById(), since it is then just another DOM object.

Upvotes: 3

Abdel Raoof Olakara
Abdel Raoof Olakara

Reputation: 19353

Refer to this article: Parsing XML response in Ajax

In this case I am using responseXML. You can make use of getElementsByTagName and other getElement*() methods to get your data.

Upvotes: 2

Related Questions