我不确定如何表达我的问题,所以我只发布我的代码并解释我要做什么:
function getNewElement(tagName, className, idName, text){
var newElement = document.createElement(tagName);
newElement.className = className;
newElement.id = idName;
newElement.innerHTML = text;
return newElement;
}
如果我打电话
getNewElement("div", "meow", "meow1", getNewElement("span","meow", "meow2", "blahblahblah"));
刚好
<div id="meow1" class="meow">[object HTMLSpanElement]</div>
所以我的问题是,我将如何编写此代码以返回一个字符串而不进行转换(可能是昂贵的操作?)或使用字符串进行 ghetto 修补。
更新: 贫民窟补丁版本:
function getNewElement(tagName, className, idName, text){
return '<' + tagName + ' class=' + className + ' id=' + idName + '>' + text + '</' + tagName + '>';
}
实现了我想要的功能,但感觉不够优雅。
最佳答案
不确定,但是如果你想在新元素#meow1
中加入#meow2
的内容,像你一样使用语句,这将是一个解决方案:
function getNewElement(tagName, className, idName, contents){
var newElement = document.createElement(tagName);
newElement.className = className;
newElement.id = idName;
newElement.innerHTML =
typeof contents === 'string' ? contents : contents.innerHTML;
return newElement;
}
现在
getNewElement("div", "meow", "meow1",
getNewElement("span","meow", "meow2", "blahblahblah"));
将创建一个新元素#meow1
,其内容为新创建的元素#meow2
。附加在文档中的某处,它看起来像:
<div class="meow" id="meow1">blahblahblah</div>
否则,如果你想让#meow2
成为#meow1
的 child ,这将是一个解决方案:
function getNewElement(tagName, className, idName, contents){
var newElement = document.createElement(tagName);
newElement.className = className;
newElement.id = idName;
if (typeof contents === 'string'){
newElement.innerHTML = contents;
} else {
newElement.appendChild(contents);
}
return newElement;
}
现在如果你愿意:
document.body.appendChild(
getNewElement("div", "meow", "meow1",
getNewElement("span","meow", "meow2", "blahblahblah"))
);
结果是这样的:
<div class="meow" id="meow1">
<span class="meow" id="meow2">blahblahblah</span>
</div>
关于javascript - 将 DOM 元素对象作为字符串返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10370751/