Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery clone div into variable and remove style attribute

Tags:

jquery

I need to remove all style attributes from a variable. I'm trying to use

someVar = $(someVar).find("*").removeAttr("style");

however this removes most of the code for some reason. It only comes back with 10 lines or so and missing out on the rest. If I do the following

someVar = $(someVar).removeAttr("style");

it only removes the first style attribute and returns everything else (as expected).

the someVar variable is basically a clone of an existing div

var someVar = $('someDiv#someID').clone();

edit: just to clarify, I want to remove the style attr from all child elements which are in the someVar variable

edit2: here's a jsfiddle https://jsfiddle.net/pscs7ttp/

like image 917
MQC Avatar asked Mar 16 '26 11:03

MQC


2 Answers

Try;

$('#element').clone().attr('style', '');

This removes style attributes in the clone, not original element. If you want to clean attributes for original element; simply switch clone and attr calls.

UPDATE: If you want remove all style attributes from all child elements, use; (note the *)

$('#element').removeAttr('style');  // remove style from self  
$('#element *').removeAttr('style'); // remove style from children

with a variable:

var variable = $('#element').clone();
// Remove children styles
variable.find('*').removeAttr('style');
// Remove self style
variable.removeAttr('style');

Run the below code to see that all styles are being removed:
(Taken from @MinusFour's answer and modified)

$(function(){
  // Clone the element
  var variable = $('#element').clone();
  // Remove children styles
  variable.find('*').removeAttr('style');
  // Remove self style
  variable.removeAttr('style');
  // Output result to see if it works
  $('#result').text(variable.prop('outerHTML'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="result"></pre>
<div id="element" style="padding:0;">
  <div style="padding:0;"></div>
  <div style="padding:0;"></div>
  <div style="padding:0;"></div>
  <div style="padding:0;"></div>
  <div style="padding:0;"></div>
  <div style="padding:0;"></div>
</div>
like image 154
tozlu Avatar answered Mar 18 '26 03:03

tozlu


    $(someVar).find("[style]").each(function(){
        $(this).removeAttr("style"));
    })
like image 36
Dipesh Gupta Avatar answered Mar 18 '26 01:03

Dipesh Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!