使用jQuery [duplicate]仅转换带div标签的img标签

问题描述 投票:1回答:1

我试图通过使用jQuery仅使用div标签转换img标签

<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标签。那可能吗?

javascript jquery html
1个回答
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?

© www.soinside.com 2019 - 2024. All rights reserved.