Home > Net >  how to get a specific tag from a html received in json
how to get a specific tag from a html received in json

Time:09-19

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.

CodePudding user response:

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);

CodePudding user response:

var main = document.getElementsByClassName('main');

for(let i = 0; i < main.length; i  ) {
  console.log(main[i]);
  for (const child of main[i].children) {
    console.log(child.innerText);
  }
}

CodePudding user response:

I solved it in a crutch way by creating a temporary div as a repository, allowing me to extract the html from it. But if anyone has a better solution, I'd love to see it.

The request has been changed to fetch.

fetch("?sections=sections_id").then(res => res.json()).then(data => {
    let section_text = data['sections_id'];
    let section_html = document.createElement("div");
    section_html.innerHTML = section_text;
    console.log(section_html.querySelector('any_selector'));                                                                                           
});
  • Related