Search code examples
jqueryrangehidechildren

Hide a certain range of children jQuery


I'm building a common header for a bunch of pages and passing in variables to set heading text, etc. I have a breadcrumb menu, and I want to only show the appropriate number of steps for the page. So here's my menu html:

<ol id="meter" class="">
<li>Page 1</li>
<li>Page 2</li>
<li>Page 3</li>
<li>Page 4</li>
</ol>

Then I have a function that looks like this:

function levels() {
$("#meter").addClass(stepNumber);
}

On Page one, I'm setting the class to "one", on page two to "two", etc.

If the class is "one", I want to show only the first item. If it's "two", I only want to show the first and second, etc.

I know I could do something with css where I write a style for each class, but that seems kind of silly. How would I do this with jQuery instead?


Solution

  • Try setting className to 1, 2 -> 100 , and utilizing :gt() Selector selector

    function levels(stepNumber) {
      $("#meter").addClass(stepNumber)
        .find("li:gt(" + (stepNumber - 1) + ")")
        .hide();
    }
    
    levels(2);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    </script>
    <ol id="meter" class="">
      <li>Page 1</li>
      <li>Page 2</li>
      <li>Page 3</li>
      <li>Page 4</li>
    </ol>

    Alternatively, to maintain adding className as one, two -> onehundred, could create an object to represent number of items to show for each class

    var keys = {
      1: "one",
      2: "two",
      3: "three",
      4: "four"
    };
    
    function levels(stepNumber) {
      $("#meter").addClass(keys[stepNumber])
        .find("li:gt(" + (stepNumber - 1) + ")")
        .hide();
    }
    
    levels(2);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    </script>
    <ol id="meter" class="">
      <li>Page 1</li>
      <li>Page 2</li>
      <li>Page 3</li>
      <li>Page 4</li>
    </ol>