我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
当前回答
function domify (str) {
var el = document.createElement('div');
el.innerHTML = str;
var frag = document.createDocumentFragment();
return frag.appendChild(el.removeChild(el.firstChild));
}
var str = "<div class='foo'>foo</div>";
domify(str);
其他回答
我正在使用这个方法(在IE9+中有效),虽然它不会解析<td>或其他一些无效的直接子体:
function stringToEl(string) {
var parser = new DOMParser(),
content = 'text/html',
DOM = parser.parseFromString(string, content);
// return element
return DOM.body.childNodes[0];
}
stringToEl('<li>text</li>'); //OUTPUT: <li>text</li>
您可以使用以下函数将文本“HTML”转换为元素
函数htmlToElement(html){var element=document.createElement('div');element.innerHTML=html;返回(元素);}var html=“<li>text和html</li>”;var e=htmlToElement(html);
我从这篇文章中得到了链接。(是否将HTML字符串转换为DOM元素?)
对我来说,我想找到一种将字符串转换为HTML元素的方法。如果您也有此需求,可以尝试以下方法
constfrag=document.createRange().createContextualFragment(`<a href=“/link.js”>js</a><a>去</a>`) constaCollection=frag.querySelectorAll(“a”)for(let[key,a]of Object.entries(aCollection)){console.log(a.getAttribute(“href”),a.textContent)}
我添加了一个Document原型,它从字符串创建一个元素:
Document.prototype.createElementFromString = function (str) {
const element = new DOMParser().parseFromString(str, 'text/html');
const child = element.documentElement.querySelector('body').firstChild;
return child;
};
用法:
document.createElementFromString("<h1>Hello World!</h1>");
实际上,我想我会分享我想出的这个过于复杂但又简单的方法。。。也许有人会发现有用的东西。
/*Creates a new element - By Jamin Szczesny*/
function _new(args){
ele = document.createElement(args.node);
delete args.node;
for(x in args){
if(typeof ele[x]==='string'){
ele[x] = args[x];
}else{
ele.setAttribute(x, args[x]);
}
}
return ele;
}
/*You would 'simply' use it like this*/
$('body')[0].appendChild(_new({
node:'div',
id:'my-div',
style:'position:absolute; left:100px; top:100px;'+
'width:100px; height:100px; border:2px solid red;'+
'cursor:pointer; background-color:HoneyDew',
innerHTML:'My newly created div element!',
value:'for example only',
onclick:"alert('yay')"
}));