Jquery clone div into variable and remove style attribute

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

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

      

however this removes most of the code for some reason. He comes back with only 10 lines or so and misses 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 variable someVar is basically a clone of the existing div

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

      

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

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

+3


source to share


3 answers


Try

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

      

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

UPDATE . If you want to remove all style attributes from all children, 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 all styles are 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>
      

Run code


+4


source


    $(someVar).find("[style]").each(function(){
        $(this).removeAttr("style"));
    })

      



+1


source


You can iterate over each object with each ():

$(function(){
  $('#d').find('*').each(function(i, el){
    $(el).removeAttr('style');
    });
  $('#result').text($('#d').html());
  });
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="result"></pre>
<div id="d">
  <div style ="st"></div>
  <div style ="st"></div>
  <div style ="st"></div>
  <div style ="st"></div>
  <div style ="st"></div>
  <div style ="st"></div>
</div>
      

Run code


Just remember that find will not select the parent (#d).

0


source







All Articles