如何使用 jQuery 在 HTML 字符串中查找元素并更改属性

How to find an element in HTML string and change an attribute using jQuery

本文关键字:元素 属性 查找 jQuery 何使用 HTML 字符串      更新时间:2023-09-26

这似乎是一个非常简单的问题,但我已经花了几个小时试图让它工作。

我有一个字符串,如下所示:

var myhtml = '<div id="wrapper"><div id="full" width="800px"></div></div>';

我需要找到我的div #full,删除它的"*width*"属性,然后在更新版本中使用 myhtml。

我在jQuery中使用它:

var newhtml = $(myhtml).filter("#full").removeAttr("width");
console.log(newhtml );

期待这个:<div id="wrapper"><div id="full"></div></div>

但它返回"<div id="full"></div>"而不是整个变量。

使用 .find("#full") 选择元素,然后删除属性。原始对象保留该值。

var myhtml = $('<div id="wrapper"><div id="full" width="800px"></div></div>');
var newhtml = myhtml.find("#full").removeAttr("width");
console.log($(myhtml)[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>