-2

I'm trying to load another page content via AJAX. It loads the content, but I have a problem with parsing new content.

Here is my code

  $.get(urlPath, function (content) {
                var newDom = $(content);
                var newTitle = newDom.find("title").text();
                console.log(newDom);
                console.log(newDom.find(CLASS.MAIN_CONTENT));
                console.log(newTitle);
                $(CLASS.MAIN_CONTENT).replaceWith(newDom.find(CLASS.MAIN_CONTENT));
            });

And this doesn't work, I get the valid content from request but still cannot get any element from new DOM Here is output of parsed with $(content)

enter image description here

And here is the raw output of the content console.log(content)

enter image description here

What can be wrong, why this doesn't work ?

2 Answers2

0

First, note that using $() to parse that HTML will throw away some of it because $() expects to be parsing body content, not a full document. So elements that seem like they should be nested within the structure may end up at the top level of the jQuery object. For instance:

var content = $(
  "<!doctype html>" +
  "<html>" +
  "<head><title>Example</title></head>" +
  "<body>" +
  "<p>Hi there</p>" +
  "</body>" +
  "</html>"
);
console.log(content.length); // 2
content.each(function() {
  console.log(this.tagName); // TITLE, P
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

find looks within the top-level elements in a jQuery object, but doesn't look at the top-level elements themselves, just their descendants. If the element matching your CLASS.MAIN_CONTENT selector is at the top level, it won't be found by find. You'd want filter instead. If it may be in either location, you want a combination of find and filter:

var mainContent = newDom.find(CLASS.MAIN_CONTENT).add(newDom.filter(CLASS.MAIN_CONTENT));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks for the answer, how can I parse new title in this case ? And I need just to add the new block with CLASS.MAIN_CONTENT selector to the existing DOM replacing the old one –  Mar 11 '17 at 12:35
  • @HelloMufecayo: I don't understand the question. You use the jQuery object you get from `filter` (or `find`, or the combination of the two)...? – T.J. Crowder Mar 11 '17 at 12:54
  • I used this solution it works fine http://stackoverflow.com/questions/30676999/parse-entire-html-document-from-string-into-jquery –  Mar 11 '17 at 14:41
0

Solution

 var newDom = $('<div></div>').append($.parseHTML(content));
                document.title = newDom.find("title").text();
                $(CLASS.MAIN_CONTENT).replaceWith(newDom.find(CLASS.MAIN_CONTENT));