是否有可能将一个DOM元素转换为另一个?或从中复制所有属性? [英] Is it possible transform one DOM element to another? Or copy all attributes from it?

查看:133
本文介绍了是否有可能将一个DOM元素转换为另一个?或从中复制所有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能将一个DOM元素转换为另一个?
通过jQuery或甚至通过JavaScript。

我只是想要例如:
获取表> thead> tr> th与所有类,属性,属性,并把它放在table> body中,就像tr> td。

或者也许是另一种方式?

解决方案

您有几个选项。


  • 您可以使用jQuery的 clone()在DOM节点上/中。然后使用 append()将克隆附加到您希望它移动到的任何元素。然后删除原来的节点。


  • 如果您只想从DOM节点(类,id等)获得属性,那么您可以使用<$所有DOM节点上存在的c $ c> attributes 数组。你必须遍历每个属性,然后单独设置新元素。我还没有找到简单的方法来复制一切。在这个看起来像这样的vanilla Javascript中:

      var originalELement = document.getElementById('original-element-id'); 
    var newElement = document.createElement('div'); (i = 0; i< originalElement.attributes.length; i ++){
    var attr = originalElement.attributes.item(i);


    newElement.setAttribute(attr.nodeName,attr.nodeValue);
    }



Is it possible transform one DOM element to another? By jQuery or even by JavaScript.

I just to want for example: get table > thead > tr > th's with all classes, attributes, properties and put it in table > body like as tr > td.

Or maybe is another way for that?

解决方案

You have a couple options.

  • You can use jQuery's clone(), which will copy everything on/in the DOM node. Then use append() to attach the clone to whatever element you want it moved to. Then just remove the original node.

  • If you just want the attributes from the DOM node (classes, id, etc.) then you can use the attributes array that is present on all DOM nodes. You'd have to loop through each attribute and then set it on the new element individually though. I have yet to find a simple way to just copy everything over. In vanilla Javascript that would look something like this:

    var originalELement = document.getElementById('original-element-id');
    var newElement = document.createElement('div');
    
    for (var i = 0; i < originalElement.attributes.length; i++) {
        var attr = originalElement.attributes.item(i);
        newElement.setAttribute(attr.nodeName, attr.nodeValue);
    }
    

这篇关于是否有可能将一个DOM元素转换为另一个?或从中复制所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆