Search code examples
javascripthtmlshopify-api

how to get a specific tag from a html received in json


I get the html sections from another page with Section Rendering API. And that works fine:

function handleResponse() {
   JSON.parse(this.responseText);
   console.log(JSON.parse(this.responseText)['sections_id']);
}  
const request = new XMLHttpRequest();
request.addEventListener('load', handleResponse);
request.open('GET', '/?sections=sections_id', true);
request.send();

Also, I insert this received html into the tag with the selector:

document.querySelector('selector').innerHTML = JSON.parse(this.responseText)['sections_id']

['sections_id'] - this is key

And that works well, too, but I have a question. For example, the structure of this received html is like this:

<div class='main'>
   <div class='item'>text</div>
   <div class='item'>text</div>
   <div class='item'>text</div>
   <img src='img.jpg' alt='img'>
</div>

But how do I get all the divisions with selector item, and also the img tag? Or get a specific selector? Thank you.


Solution

  • You can use a DOMParser for this.

    let responseHTML = `<div class='main'>
       <div class='item'>text item 1</div>
       <div class='item'>text item 2</div>
       <div class='item'>text item 3</div>
       <img src='img.jpg' alt='img'>
    </div>`;
    
    const DOM = (new DOMParser()).parseFromString(responseHTML, 'text/html');
    
    const items = DOM.querySelectorAll('.item, img');
    
    document.body.append(...items);