Search code examples
javascriptjqueryhtmlget

How get HTML without remove child (jQuery)


There are some problems with changing the js-object. It has the html structure. Example:

myObj.html ='<span class="first">la-la-la</span>
            <span class="second">la-la-la</span>';

And structure due to user actions is changing( add,delete elements ):

$(myObj.html).find('.second').remove()

Theoretically it has to help. But I work with just string (it is not real DOM element). myObj.html don't save changing, and .remove() return deleted element. And I want that myObj.html changed too:

myObj.html ='<span class="first">la-la-la</span>;

How to be in this situation? (RegExp is not better idea)


Solution

  • If you call .html(myObj.html) on a temporary element, you can do whatever you want, then read it back afterwards:

    var myObj = {};
    
    myObj.html ='<span class="first">la-la-la</span><span class="second">la-la-la</span>';
    
    $tmp = $("<div>").html(myObj.html);
    $tmp.find(".second").remove();
    myObj.html = $tmp.html(); 
    
    console.log(myObj);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>