Search code examples
htmljquerystringdomdom-manipulation

jQuery to manipulate temporary DOM as HTML string


I was following up with the solution here jQuery - Insert text inside element of a HTML string which is quite similar to my problem, but I was not able to make it work.

Problem Definition:

I get some HTML from some external code, which I store into a variable. The HTML is as follows:

<div class="A2_B3" id="A2_B3">
    <div class="symptom">Symptom 1</div>
</div>
<div class="A2_B1" id="A2_B1">
    <div class="symptom">Symptom 2</div>
</div>

I store this HTML into a variable called "tmp_dom_html".

My job:

(1) Check whether class="A2_B3" has a next div with class="connected". If found, the add myHtml in it.

(2) If class="A2_B3" does not have the next div with class="connected", the append a div with class called "connected" with myHtml into it.

var myHtml = '<p>Bla Bla Bla</p>';

Finally the HTML should look like this:

<div class="A2_B3" id="A2_B3">
    <div class="symptom">Symptom 1</div>
</div>
<div class="connected"><p>Bla Bla Bla</p></div>
<div class="A2_B1" id="A2_B1">
    <div class="symptom">Symptom 2</div>
</div>

Here is my code and nothing seems to work. Can anybody help me with the problem.

<script type="text/javascript">
var tmp_dom_html = '<div class="A2_B3" id="A2_B3"><div class="symptom">Symptom 1</div></div><div class="A2_B1" id="A2_B1"><div class="symptom">Symptom 2</div></div>';

var new_dom_html = $(tmp_dom_html);
var myHtml = '<p>Bla Bla Bla</p>';
//If the div with class="connected" is found, like this <div class='connected'></div> but without anything isnide it
new_dom_html.find(".A2_B3").next(".connected").append(myHtml);

if(!new_dom_html.find(".A2_B3").next().hasClass(".connected")){
    new_dom_html.find(".A2_B3").after("<div class='connected'>"+myHtml+"</div>");
}
alert($(new_dom_html).html());

Solution

  • Use a DOMParser.

    const data = new DOMParser().parseFromString(`<div class="A2_B3" id="A2_B3"><div class="symptom">Symptom 1</div></div><div class="A2_B1" id="A2_B1"><div class="symptom">Symptom 2</div></div>`, "text/html");
    const selected = $(data.body);
    $('.A2_B3', selected).each(function(){
      if(!$(this).next().hasClass('connected')){
        $(this).after('<div class="connected"><p>Bla Bla Bla</p></div>');
      }
    })
    console.log(selected[0].innerHTML);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>