【问题标题】:TypeError: (intermediate value).parseFromString(...).replace is not a functionTypeError: (intermediate value).parseFromString(...).replace 不是函数
【发布时间】:2022-01-17 20:12:31
【问题描述】:

我想将 parsedHtml 显示到元素中。但在显示之前,我应该将一点 html 更改为 parsedHtml。所以我用替换这个类似的代码。但它有TypeError: (intermediate value).parseFromString(...).replace is not a function 问题。你能帮我解决这个问题吗?谢谢

const parsedHTML = new DOMParser().parseFromString(html, "text/html");
const renderHtml = parsedHTML.replace('aria-expanded="false"', 'aria-expanded="true"');
console.log(renderHtml);

【问题讨论】:

  • 看来问题是因为 .replace() 是一个字符串函数。 parsedHTML 变量不是字符串而是 DOMParser 对象,因此 .replace() 不是可用函数。您可能需要在名为 html 的变量上运行 .replace() 函数,然后将其传递给 parseFromString() 函数。

标签: javascript dom typeerror


【解决方案1】:

您将 DOMParser 对象视为字符串。那是行不通的。

您需要这样做,因为不建议您在解析之前更改有效的 HTML

const html = `<html><div aria-expanded="false"></div></html>`
const parsedHTML = new DOMParser().parseFromString(html, "text/html");
parsedHTML.querySelector("div").setAttribute("aria-expanded",true)
console.log(parsedHTML.querySelector("div"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多