SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    338
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Get all data- attributes

    Is there a way (jQuery is fine) to get all the data- attributes on a page and then change the values in the element's class to those in the data- attribute?
    E.g.

    this:
    Code:
    <div class="class1 class 2">
    A
    </div>
    <div class="class1 class 2" data-class-override="class3 class 4">
    B
    </div>
    <div class="class1 class 2">
    C
    </div>
    ...becomes:

    Code:
    <div class="class1 class 2">
    A
    </div>
    <div class="class3 class 4">
    B
    </div>
    <div class="class1 class 2">
    C
    </div>
    I need it to search the entire page as they could be anywhere.

    I know $(this).data("class-override") would get it but how search the whole page and how do it in the best way?

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,347
    Mentioned
    179 Post(s)
    Tagged
    9 Thread(s)
    Don't know if this is the best way, but it works:


    HTML Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Unbenanntes Dokument</title>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
      </head>
      
      <body>
        <div class="class1 class 2">A</div>
        <div class="class1 class 2" data-class-override="class3 class 4">B</div>
        <div class="class1 class 2">C</div>
        
        <script>
          $(document).ready(function() {
            $("body").find('[data-class-override]').each(function(){
              $(this).removeClass();
              $(this).addClass($(this).attr('data-class-override'));
              $(this).removeAttr('data-class-override');
            });
          });
        </script>
      </body>
    </html>


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
  •