1、字符串转换成代码
//字符串转换成代码
let stringHtml = '<!DOCTYPE html><html lang="zh-CN">
<head>
<meta http-equiv="x-ua-compatible" content="ie=edge, chrome=1">
<meta charset="UTF-8">
<meta name="renderer" content="webkit">
<meta name="author" content="WebpowerChina">
<link rel="WebpowerChina" href="mailto:[email protected]">
</head>
<body>
<div>
<input type="text" value="hellow">
</div>
</body>
</html>'
// StringHTMl to html
let codeHtml = new DOMParser().parseFromString(stringHtml, 'text/html');
console.info(codeHtml);
打印结果如图:
2、dom元素转化成字符串
let dom = document.getElementsByClassName('activeBlock')[0];
// 选中的区域块 input dom元素转化成字符串
let inputHtml = dom.querySelector('input').outerHTML;
3、innerHTML与outerHTML的区别
<template>
<div style="">
<div>
<p>你好</p>
<div id="html">
<h3>hellow world</h3>
</div>
</div>
</div>
</template>
export default {
mounted(){
let inHtml = document.getElementById('html').innerHTML;
let outHtml = document.getElementById('html').outerHTML;
console.info(inHtml, typeof inHtml, 'inHtml');
//<h3>hellow world</h3> string inHtml
console.info(outHtml, typeof outHtml, 'outHtml');
//<div id="html"><h3>hellow world</h3></div> string outHtml
}
}
如图: