javascript - 将 DOM 元素对象作为字符串返回?

标签 javascript html dom

我不确定如何表达我的问题,所以我只发布我的代码并解释我要做什么:

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/

相关文章:

javascript - 从传单弹出窗口内的复选框访问功能

javascript - 如何将所有 html 标签从 <anything> 替换为\n<anything>\n [使用正则表达式 (JavaScript)]

javascript - 为什么我们能够在 React 组件的构造函数中绑定(bind)函数?

php - laravel 插入多个输入

javascript - 我可以用另一个 Javascript 从 DOM 中删除一个 javascript 吗?

jquery - 如何在不削弱 CPU 的情况下向 IE 添加大量 HTML

javascript - 如何从发出警报的页面恢复 "text",尤其是在人类用户在页面的 **警报** 上 *单击* 后?

jQuery 禁用带有 prop 或 attr 的链接元素

php - 如何在 php 中创建 html 表

javascript - 无法设置表单输入javascript的值