Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Mar 2012
    Posts
    81
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Remove ALL attributes

    I can't seem to find a simple way to do this.

    $('.section').removeAllAttr() would be nice.

    $('.section').removeAttr() doesn't work where I thought it might.

    So,
    Code:
    <div class="section hello" data-test="123" id="an-id" data-something="abc">
    content
    </div>
    ...results in...
    Code:
    <div>
    content
    </div>
    It needs to work for any tag as well.

    Surely this should be easy but I just can't do it.

    If it's easier (or quicker for jQuery) then removing all the data- attributes is fine, as I could then do this:
    Code:
    $('.section').removeAllDataAttributes().removeClass();
    ...which would be fine for what I need.

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    This little plug-in should be able to help you
    Code:
    jQuery.fn.removeAttributes = function() {
      return this.each(function() {
        var attributes = $.map(this.attributes, function(item) {
          return item.name;
        });
        var elem = $(this);
        $.each(attributes, function(i, item) {
          elem.removeAttr(item);
        });
      });
    }
    Then you can just call
    Code:
    $('.section').removeAttributes();

  • #3
    New Coder
    Join Date
    Mar 2012
    Posts
    81
    Thanks
    7
    Thanked 0 Times in 0 Posts
    Great thanks.

    I actually saw that on Google somewhere but it looks too long winded. As long as it's as quick as a built-in jQuery function then I'm fine. Is it as quick? I have no idea.

    Is there a quicker way at all?

    I don't want to implement something for this that will slow the initial load down.

  • #4
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    A lot of the jQuery calls would run a lot more JavaScript in the browser than that - jQuery runs lots of JavaScript in order to save you from having to write it yourself.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •