SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Remove ALL attributes in jQuery

    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. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,941
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    Unfortunately, there's nothing like $('.section').removeAllAttr()
    But, you can do it like this:

    Code JavaScript:
    $(document).ready(function() {
      $('div').each(function() {
        var attributes = this.attributes;
        var i = attributes.length;
        while( i-- ){
          this.removeAttributeNode(attributes[i]);
        }
      })
    });

  3. #3
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Brilliant, thanks.

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,716
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    The following is a much simpler way of achieving the same result.

    Code javascript:
    $('.section').replaceWith(function () {
        return $('<div>').append($(this).contents());
    });

    Or if you want to make it fully generic, so that it uses the same element, you can use this.nodeName instead:

    Code javascript:
    $('.section').replaceWith(function () {
        return $('<' + this.nodeName + '>').append($(this).contents());
    });
    Last edited by paul_wilkins; Dec 12, 2012 at 15:53.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  5. #5
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,941
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Excellent


Bookmarks

Posting Permissions

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