skip to Main Content

I’m adding new content display by getting an html snippet from the server and applying some changes in it. However I can’t change the jquery object created and I don’t understand why. I’ve seen lots of similar questions to mine but I don’t think they apply to my case.

The html returned from this GET request is in this format:

<div>
 <!-- more content-->
 <div class="row">
  <div class="col-sm-12">
   <span class="post-conteudo">SOME TEXT I WANT TO CHANGE</span>
  </div>
 </div>

</div>

My code is:

$.get( `/myUrl`, function( data ) {
 if(data){
   internalContent = $($(data).find('.post-conteudo')[0]).html();
   treatedContent = applyChanges(internalContent);
                
   $($(data).find('.post-conteudo')[0]).html(treatedContent)

   localStorage.setItem(`data-post-${idPostCitado}`, data);
                
 }
});

When debugging I see that internalContent is equal to SOME TEXT I WANT TO CHANGE so I assume I’m correctly referencing the internal element. But when I try to change it, it does,’t change and data remains as before.

2

Answers


  1. The issue lies in how you’re trying to manipulate the HTML content within data. Here’s the core problem:

    When you retrieve data from the server in the $.get callback, it is a string containing HTML, not an actual DOM element. Therefore, jQuery operations like $(data).find('.post-conteudo') work on a temporary, detached jQuery object, not the original data. Any changes you make to this jQuery object do not affect the original string data.

    To work with the HTML as a manipulatable structure, parse it into a DOM-like format using jQuery or native DOM methods. Here’s how you can fix your code:

    $.get(`/myUrl`, function(data) {
        if (data) {
            let parsedData = $($.parseHTML(data));
            let internalContent = parsedData.find('.post-conteudo').html();
            let treatedContent = applyChanges(internalContent);
            parsedData.find('.post-conteudo').html(treatedContent);
            let updatedData = parsedData.prop('outerHTML');
            localStorage.setItem(`data-post-${idPostCitado}`, updatedData);
        }
    });
    
    Login or Signup to reply.
  2. $(data) creates a jQuery instance, but it doesn’t manipulate data.

    You can do it this way:

    data = $(data);
    data.find('.post-conteudo').eq(0).html(treatedContent);
    data = data.html();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search