我正在尝试使用jQuery转换img tag wit div标签
<img class="wrap" src="xyz.com" alt="test" />
<div class="test"></div>
带
<div class="wrap" src="xyz.com" alt="test" />
尝试这样
var $select = $(".wrap");
var $div = $(".test");
var attributes = $select.prop("attributes");
$.each(attributes, function() {
$div.attr(this.name, this.value);
});
上面的代码是从img复制所有属性并分配给div标签。我希望在不指定html的情况下实现相同目标。我只想用div标签替换img标签。这可能吗?
答案 0 :(得分:1)
试试这个:
var $img = $("img.wrap");
var $div = $("div");
var attributes = $img.prop("attributes");
// loop through <img> attributes and apply them on <div>
$.each(attributes, function() {
$div.attr(this.name, this.value);
});
$img.remove();
$("#someContainer").append($div);
HTML:
<div id="someContainer">
<img class="wrap" ... />
</div>
来源:jQuery: How to copy all the attributes of one element and apply them to another?