Skip to content

targeting dom elements with data attributes with a value of (n) #1267

Closed

Description

@heaversm

I have a navigational menu which assigns an array of colors to menu items based on their depth within a menu hierarchy / taxonomy. So, for example, all top level menu items get a color of black, next level gets red, next level gets green, etc, and because the hierarchy goes very deep, I'd like to target them using math, sort of the way that css can target nth-child. However, I can't use nth-child because these container elements ('browse-level') are dynamically added and removed from the DOM (they're not all in the DOM at the same time) which is why I'm target data attributes.

So here's the CSS:

    .browse-level[data-level="1"] li a {
      background: @level1;
    }

    .browse-level[data-level="2"] li a {
      background: @level2;
    }

    .browse-level[data-level="3"] li a {
      background: @level3;
    }

    .browse-level[data-level="4"] li a {
      background: @level4;
    }

... etc

There are 8 color values (after which the sequence would repeat). Can I (using LESS or plain CSS) shorten this code?

Activity

  1. lukeapage commented on Apr 15, 2013

    @lukeapage
    Member

    in 1.4.0

    .browse-mixin(@level) when (@level > 0) {
        @attr: ~'data-level="@{level}"';
        .browse-level[@{attr}] li a {
             @varname: "level@{level}";
             background: @@varname;
        }
        .browse-mixin((@level - 1));
    }
    .browse-mixin(4);
    @level1: a;
    @level2: b;
    @level3: c;
    @level4: d;
    

    in 1.3.3

    .browse-mixin(@level) when (@level > 0) {
        @attr: ~'.browse-level[data-level="@{level}"]';
        @{attr} li a {
             @varname: "level@{level}";
             background: @@varname;
        }
        .browse-mixin((@level - 1));
    }
    .browse-mixin(4);
    @level1: a;
    @level2: b;
    @level3: c;
    @level4: d;
    

    ??

  2. jonschlinkert commented on Apr 15, 2013

    @jonschlinkert
    Contributor

    this is a good question for stackoverflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions