【问题标题】:How can I parse a string representation of an element into an actual html element?如何将元素的字符串表示解析为实际的 html 元素?
【发布时间】:2017-08-02 21:38:17
【问题描述】:

例如,如果我有:

'<html><body><p>hello</p></body></html>'

如何将其解析为实际的 html 元素?

我尝试过类似以下的方法:

getNodeType(element) {
  const temp = document.createElement('div');
  temp.innerHTML = element;
  if (temp.firstChild) return temp.firstChild.nodeName;
  else return null;
}

效果很好,但我无法解析 <html><body><title> 等标签,因为它们无法包含在 div 中。我也尝试过 DOMParser,但它将所有内容都包装在 html、head 和 body 标记中,因此我无法识别实际元素。

宁愿不使用jQuery,但也不完全反对。

非常感谢任何建议,非常感谢!

【问题讨论】:

  • 什么意思:我怎样才能把它解析成一个实际的 html 元素?
  • 尝试使用jQuery.parseHTML(data, [, context] [,keepScripts])

标签: javascript html


【解决方案1】:

您应该为此使用 DOMParser:

parser = new DOMParser();
doc = parser.parseFromString('<html><body><p>hello</p></body></html>', 'text/html');
console.log(doc.getElementsByTagName('p')[0])
// will print: <p>hello</p>

更多信息在这里:https://developer.mozilla.org/en/docs/Web/API/DOMParser

【讨论】:

  • 与我上面的评论相同的问题 - 有什么想法吗?
  • 嗯,您是说在您的情况下,此解决方案没有将“

    hello

    ”打印到控制台?或者您需要通过某些属性来区分内部标签?我想你应该看看这三个方法:getElementById()、getElementsByClassName()、getElementsByTagName()。如果您有任何问题,请告诉我。
【解决方案2】:

不知道你为什么对DOMParser 有问题,它应该可以正常工作

const parser = new DOMParser();
const doc = parser.parseFromString('<html><body><p>hello</p></body></html>', 'text/html')
console.log(doc.firstChild.nodeName);

【讨论】:

  • DOMParser 的问题实际上是它在我定位的元素周围添加了 HTML 和 head 或 body 标签,所以 firstChild 总是返回 html。有关如何解决此问题的任何想法?
猜你喜欢
  • 1970-01-01
  • 2013-09-13
  • 2021-09-19
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多