简体   繁体   中英

jQuery replaceWith not working without DOM

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.

In a very simple example, I want to do something like this... where I find all the div elements and replace with spans .

const html = '<html><div>hello</div><div>hello</div></html>';
const obj = $(html);
const filter = $(obj).find('div');

for (let j = filter.length; j >= 0; j--) {
  $(filter[j]).replaceWith("<span>goodbye</span>");
}

console.log(obj);

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.

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.

I want the console here to show the HTML element with two spans rather than two divs , 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.

http://jsfiddle.net/vkn285a1/1/

** UPDATE **

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

  const html = "<svg><g><text>hello</text><text>hello</text></g></svg>";
  const obj = $.parseHTML(html);

  const filter = $(obj).find("text");

  for (let j = filter.length; j >= 0; j--) {
    $(filter[j]).replaceWith("<span>goodbye</span>");
  }

在此处输入图像描述

Your issue is following:

const obj = $(html);

this obj is NULL.

You have to use parseHTML function to get object from string as following.

const html = '<html><div>hello</div><div>hello</div></html>';
const obj = $.parseHTML(html);

Then obj will be an array of divs in html tag of string.

在此处输入图像描述

After that, you can try anything for those objects that are not NULL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM