Search code examples
jqueryinnerhtml

Using $.get to import contents from specific divs on another page and insert them into 2 divs


External page from which I'd want to import data looks like this:

<div id="cont1">something</div>
<div id="cont2">something else</div>

I am using this code to get the contents:

$.get("page.html", function(data) {
  $("#container1").html(data);
  $("#container2").html(cont2);
});

It works but not quite right since it's importing the containers too. How can I import only contents, not containers?


Solution

  • Your $.get() callback is importing the containers too because the complete response data (which includes the two outer <div>s) is being set as innerHTML.

    To append only the contents without their containers:

    • Parse the data html string using jQuery

      const $data = $(data);
      
    • Filter the two divs using their #ids

      $data.filter("#cont1")
      $data.filter("#cont2")
      

      This is the tricky part! If you try to extract the containers using find() as described in other linked questions, the extraction will fail silently as find() returns an empty jQuery collection here.

      $data.find("#cont1").length == 0 // true
      $data.find("#cont1").html() == undefined // true
      

      This is because there's no root element present in data, both the <div>s are siblings to each other.

    • Copy their innerHTML contents to current document's containers

      $("#container1").html($data.filter("#cont1").html());
      $("#container2").html($data.filter("#cont2").html());
      

    The following is a complete example of parsing inner content as outlined above. Please ignore all the testdouble's td calls, that's just there to prepare the test case to respond with a mock AJAX response when the $.get() call is received.

    // Stub AJAX reponse
    td.when(td.replace($, "get")("page.html")).thenCallback(`
        <div id="cont1">
            <b>testdouble.js</b> (td.js)
        </div>
        <div id="cont2">
            <i>Mocking library for JavaScript tests</i>
        </div>
    `);
    
    // Test response parser
    $.get("page.html", function(data) {
      const $data = $(data);
      console.log($data.find("#cont1").length); // 0
      $("#container1").html($data.filter("#cont1").html());
      $("#container2").html($data.filter("#cont2").html());
      console.log($("#containers").prop("outerHTML"));
    });
    
    td.reset();
    <html>
    <head>
      <title>Parse AJAX Response Test</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://unpkg.com/testdouble@3.16.1/dist/testdouble.js"></script>
    </head>
    <body>
      <div id="containers">
        <div id="container1"></div>
        <div id="container2"></div>
      </div>
    </body>
    </html>