How can I extract a certain element from an html string returned by AJAX?

1

As I say in my question.

What happens is that through Ajax I make a call to an HTML document, but I only want to obtain a certain element, let's say that only the content of the body.

How can I do it?

Well, what I'm trying to do is implement the navigation using the'History' api of javascript, and I want to get only a specific content and put it in a specific div.

    
asked by Eddy Otsutsuki 05.02.2018 в 00:36
source

2 answers

2

Since you do not always have control over ids on other pages, it might be interesting for you to use $.get .

So, you can work with the answer. You can create a DOM with the answer using DOMParser and access the body using elementoDOM.body , or any element without having to depend on it having an id or a selector.

Let's see a test, putting the body of the answer in div whose id is resultado :

var url = 'https://www.w3.org/TR/xhtml1/';
$.get(url, function(data) {
  DOMparser = new DOMParser();
  DOMdata = DOMparser.parseFromString(data, 'text/html');
  var bodyHTML = DOMdata.body;

  /*En el caso de elementos como body deberás usar replace, para que no lo duplique*/

  //  $('body').replaceWith(bodyHTML);
  $('#resultado').html(bodyHTML);
  console.log(bodyHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resultado"></div>

Now an example using $.ajax :

/*Usando $.ajax*/
var url = 'https://developer.mozilla.org/es/docs/Web/HTML';
var request = $.ajax({
  url: url,
  method: "GET",
  dataType: "html"
});

request.done(function(data) {
  DOMparser = new DOMParser();
  DOMdata = DOMparser.parseFromString(data, "text/html");
  var bodyHTML = DOMdata.body;
  $('#resultado').html(bodyHTML);
});

request.fail(function(jqXHR, textStatus) {
  alert("Error : " + textStatus);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resultado"></div>

NOTE:

In the specific case of body , if you do this:

  $("body").html(bodyHTML);

will double the body .

You should use in that case:

  $("body").replaceWith(bodyHTML);
    
answered by 05.02.2018 / 02:21
source
1

You can use the load function of Jquery to get the content of an external html page and add the content to a div, for example, of the current document:

$( "#divactual" ).load( "pagina.html #bodydeldocumento" );

You need to add an identifier to the part of the other document you want to access, in the example #bodydeldocumento, it refers to:

<body id="bodydeldocumento"></body>

Using ajax would look something like this:

 $.ajax({
     url: 'pagina.html',
     success: function(response) {
       $( "#divactual" ).load( "pagina.html #bodydeldocumento" );
     }
 });
    
answered by 05.02.2018 в 00:50