簡體   English   中英

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

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

這似乎是一個非常簡單的問題,但是我已經花了幾個小時試圖使它起作用。

我有一個像這樣的字符串:

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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM