如何在javascript中从字符串传递到对象

nzkunb0c  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(311)

我有以下javascript代码。

var abc = `<div class="hello" data-id="99" data-price="100" data-category="mal">
        <div class="hello-category">Hello word</div>
        <div class="hello-description"><h2>The best burger in town 12345615</h2></div>
        </div>`;

我想得到以下结果:

<div class="hello" data-id="99" data-price="100" data-category="mal">
vh0rcniy

vh0rcniy1#

你可以使用 DOMParser :

var abc = `<div class="hello" data-id="99" data-price="100" data-category="mal"><div class="hello-category">Hello word</div><div class="hello-description"><h2>The best burger in town 12345615</h2></div>`;
const parser = new DOMParser().parseFromString(abc, "text/html");
parser.body.firstChild.innerHTML=''; //<-- remove innerhtml of the div
const result = parser.body.innerHTML; //<-- get result
console.log(result);
lnvxswe2

lnvxswe22#

您可以将其转换为dom节点,然后对其执行dom操作,如下所示

const abc_string = `<div class="hello" data-id="99" data-price="100" data-category="mal">
        <div class="hello-category">Hello word</div>
        <div class="hello-description"><h2>The best burger in town 12345615</h2></div>
        </div>`;

//  convert string to DOM node
const abc_node = new DOMParser().parseFromString(abc_string, 'text/html').body.firstChild;

//  iterate over child nodes, removing them each time
Array.from( abc_node.childNodes ).forEach(thisChild => {
   abc_node.removeChild( thisChild );
});

//  what you have left
console.log(abc_node);

相关问题