title: jQuery replaceWith not working without DOM
body: <p>I am trying to do some element manipulation on a Node.js server where I need to take a string of HTML, then replace some of the nodes with other node types. This was working fine when I was doing it with a DOM but as soon as I don't have a DOM it does not work.</p>
  
  <p>In a very simple example, I want to do something like this... where I find all the <code>div</code> elements and replace with <code>spans</code>. </p>
  
  <pre><code>const html = '&lt;html&gt;&lt;div&gt;hello&lt;/div&gt;&lt;div&gt;hello&lt;/div&gt;&lt;/html&gt;';
  const obj = $(html);
  const filter = $(obj).find('div');
  
  for (let j = filter.length; j &gt;= 0; j--) {
    $(filter[j]).replaceWith("&lt;span&gt;goodbye&lt;/span&gt;");
  }
  
  console.log(obj);
  </code></pre>
  
  <p>I can't just do a find and replace on the string as I don't want all elements I am doing a filter based on various things before I do this.</p>
  
  <p>It is not working saying that the node is not an element. Is there a way I can do this? I have also tried using JSDOM to do this but again, no luck.</p>
  
  <p>I want the console here to show the HTML element with two <code>spans</code> rather than two <code>divs</code>, I have tried adding a jsfiddle for this however I am getting a different error on here too, if anyone can help it would be appreciated.</p>
  
  <p><a href="http://jsfiddle.net/vkn285a1/1/" rel="nofollow noreferrer">http://jsfiddle.net/vkn285a1/1/</a></p>
  
  <p>** <strong>UPDATE</strong> **</p>
  
  <p>From the answer below, I have updated but I am now getting my desired result, thank you.. I had to change to use SVG which is what I am actually parsing and it worked a treat</p>
  
  <pre><code>  const html = "&lt;svg&gt;&lt;g&gt;&lt;text&gt;hello&lt;/text&gt;&lt;text&gt;hello&lt;/text&gt;&lt;/g&gt;&lt;/svg&gt;";
    const obj = $.parseHTML(html);
  
    const filter = $(obj).find("text");
  
    for (let j = filter.length; j &gt;= 0; j--) {
      $(filter[j]).replaceWith("&lt;span&gt;goodbye&lt;/span&gt;");
    }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/MQJ1B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MQJ1B.png" alt="enter image description here"></a></p>