我希望能够像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'));
答案 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 );