I have checked Google and answers and tutorials, I know how to get only a part of a file by AJAX using jQuery, but I could not find any instructions on how to do it with plain JS.
I have tried:
xhr.open('GET', 'https://website.html .my-class');
Does not work, lookign for an element by ID did not work either.
xhr.open('GET', 'https://website.html');
This returns the whole file.
I have not tried to cache and fragment the whole returned file, I doubt that would work anyway.
So, how is this done? Certainly it's possible, right?
You can use DOMParser()
to create an HTML document
from XMLHttpRequest.responseText
, then use document.querySelector()
or document.querySelectorAll()
to retrieve the specific selectors from document
var file = `data:text/html, <!DOCTYPE html> <html> <body> <div class="my-class">my class</div> </body> </html>`; var request = new XMLHttpRequest(); request.open("GET", file, true); request.onload = function() { var html = request.responseText; var parser = new DOMParser(); var doc = parser.parseFromString(html, "text/html"); var el = doc.querySelector(".my-class"); document.body.appendChild(el); } request.send();
I recommend you use jquery. Less time.
Alternatively you can use the DOMParser
object of web API.
https://developer.mozilla.org/it/docs/Web/API/DOMParser
this parse your file text/html, then you can search for the class you want
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.