与HTML字符串交互就好像它是文档一样?

时间:2017-10-22 08:13:32

标签: javascript html dom

我希望能够像HTML document一样与HTML字符串进行交互。类似的东西:

    var html_string = '<!DOCTYPE html><html><head><title>Page Title</title></head><body><h1 id="id1" class="test test2">This is a Heading</h1><p id="id2" class="test">This is a paragraph.</p></body></html>'

console.log(html_string.getElementById('id1'));
console.log(html_string.getElementsByClassName('test'));
console.log(html_string.querySelector('.test.test2'));

1 个答案:

答案 0 :(得分:5)

您可以使用本机DOMParser解析HTML字符串:

var html_string = '<!DOCTYPE html><html><head><title>Page Title</title></head><body><h1 id="id1" class="test test2">This is a Heading</h1><p id="id2" class="test">This is a paragraph.</p></body></html>'

var doc = new DOMParser().parseFromString(html_string,"text/html")
                            
console.log(doc.getElementById('id1').innerHTML );
console.log(doc.getElementsByClassName('test')[0].innerHTML  );
console.log(doc.querySelector('.test.test2').innerHTML );