Take HTML elements from a url and send to a div

Asked

Viewed 984 times

1

How to pick up elements with a id specifies, and take all the elements that are within a url and send to a div(nay iframe)? Is it possible with pure Javascript, or do I need a js library? Where do I start?.
Example I want to get elements of this url https://sopt.stackexample.ml/copiar.html or that https://sopt.stackexample.ml/copiar and send to a div

Example of where I want to get, but using an element on the same page:

function copiar() {
  document.getElementById("div1").innerHTML = document.getElementById("div").innerHTML
}
<button onclick="copiar()">CLIQUE</button>
<div id="div">Texto</div><div id="div1"></div>

NOTE: I have access to the page where I want to get the elements

1 answer

2

You can use the XMLHttpRequest or Fetch to make a request to get source code from the page. After that, just use document.createElement or DOMParser to be able to "convert" the returned source code (such as string) for HTML.


Example with XMLHttpRequest and document.createElement:

XMLHttpRequest is an API that provides client functionality to transfer data between a client and a server. It provides an easy way to recover data from a URL without having to do a full page update. Already the document.createElement will create an element HTML, in this way we can use functions such as querySelector and filter certain elements.

Javascript:

const result = document.querySelector("#result")
const xhr = new XMLHttpRequest();

xhr.addEventListener("load", event => {

  /**
   * Cria um elemento temporário
   * Adiciona o código fonte retornado
   */
  const html = document.createElement("html")
  html.innerHTML = event.target.response

  /* Captura todos os links com o atributo rel="bookmark" */
  const anchors = html.querySelector("a[rel=\"bookmark\"]");

  /* Adiciona os links capturados na div#result */
  anchors.forEach(anchor => {
    result.innerHTML += anchor
  })

})

function copy() {
  /* Realiza a requisição */
  xhr.open("GET", "https://developer.mozilla.org/en-US/")
  xhr.send()
}

Javascript:

<button onclick="copy()">Click!</button>

<div id="result"></div>

Example with Fetch and DOMParser:

To Fetch API provides an interface to search for resources (for example, across the network). It will look familiar to anyone who has used Xmlhttprequest, but the new API offers a more powerful and flexible feature set. The function DOMParser will convert our string for HTML, in this way we can use functions such as querySelectorAll to filter useful elements.

Javascript:

const result = document.querySelector("#result")

function copy() {
    fetch("https://developer.mozilla.org/")
        .then( response => response.text())
        .then( response => {

            /**
            * Cria um elemento temporário
            * Adiciona o código fonte retornado
            */
            const parser = new DOMParser()
            const html = parser.parseFromString(response, "text/html")

            /* Captura todos os links com o atributo rel="bookmark" */
            const anchors = html.querySelector("a[rel=\"bookmark\"]")

            /* Adiciona os links capturados na div#result */
            anchors.forEach(anchor => {
                result.insertAdjacentHTML('beforeend', anchor)
            })
        })
}

HTML:

<button onclick="copy()">Click!</button>

<div id="result"></div>

Restriction:

For security reasons, browsers are blocking requests on pages that do not have the header Access-Control-Allow-Origin.

Diagrama de Uso

For more details recommend the page HTTP Access Control (CORS).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.