简体   繁体   中英

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

This seems to be a very simple question but I've been at it for a couple of hours trying to make it work.

I have a string like:

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

I need to find my div #full , remove it's "*width*" attribute and then use myhtml with the updated version.

I'm using this in jQuery:

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

Expecting this: <div id="wrapper"><div id="full"></div></div>

But it returns "<div id="full"></div>" and not the whole variable.

Use .find("#full") to select the element then remove attribute. The original object retains the value.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM