0

I have a couple of links like the following. My JS method returns either "days" or "week". Based on that return value I want to assign class="active" to one of these where data-period value matches return value. Can someone please suggest 1-2 line JS code to achieve this.

 <a href="#" class="hourlyChartPeriod" data-period="days">D</a>
 <a href="#" class="hourlyChartPeriod" data-period="week">W</a>
3
  • 2
    Post your other JS method, and what you've tried. Commented Aug 21, 2014 at 19:01
  • Yes, I am using JQuery. Please suggest. Commented Aug 21, 2014 at 19:11
  • Sir tymeJV, because I could not find anything to try on these lines. Are you offended ? Commented Aug 21, 2014 at 19:12

5 Answers 5

2

This is quite simple when using JQuery:

$("a[data-period='" + someMethod() + "']").addClass("active");

This of course assumes your method that, "returns either 'days' or 'week'" is called someMethod.

Here's a CodePen demo.

If you also need to ensure that the other non-matching elements don't have the active class, remove it from them as well. There's a few ways to do this. This one's nice and clean:

$("a[data-period]").removeClass("active");
$("a[data-period='" + someMethod() + "']").addClass("active");

...and this is a little further optimized:

$("a[data-period]")
    .removeClass("active")
    .filter("a[data-period='" + someMethod() + "']")
    .addClass("active");

...because instead of re-selecting from the DOM again, it will reuse those initial a[data-period] results. Sadly it still results in removing the class from the elements that will end up having it anyway. But it really doesn't matter if you don't have a ton of elements (read: hundreds) that have a data-period.

Still, if you want (or need) to be a stickler about it, this is even further optimized:

$("a[data-period].active")
    .not($("a[data-period='" + someMethod() + "']").addClass("active"))
    .removeClass("active");

...but even harder to read.

Sign up to request clarification or add additional context in comments.

3 Comments

That's how I roll, yo. ;) Thanks.
Just one more thing .. how can we append an id as well to that selection. I have different links with different ids and I just want to do it for a particular id.
You mean you want it to end up like <a href="#" class="hourlyChartPeriod" data-period="days" id="whateverValueYouWant">D</a>? Just add .attr("id", "whateverValueYouWant") after .addClass("active"). As a reminder, be careful to make sure your ID's are always unique.
0
jsReturnValue="The Return Value From Your JS Script"

var elems=Array.prototype.slice.call(document.querySelectorAll('.hourlyChartPeriod'));

var elem=elems.filter(function(e){return e.getAttribute('data-period')===jsReturnValue});

elem.classList.add('newClass')


// or you could use jQuery - which I suspect you might be

  var elems=jQuery('.hourlyChartPeriod');
  elems.filter(function(){
           return $(this).data('period')===jsReturnValue;
  }).addClass('yourNewClass');

1 Comment

Thanks a lot. Can you please share JQuery version of this as well.
0

You could try this:

<script type="text/javascript">
    var a = document.getElementsByTagName("a");
    for(var i = 0; i < a.length; i++) {
        if(a[i].getAttribute("data-period")) {
            if(a[i].getAttribute("data-period") == <YOUR_VALUE>)
                a[i].classList.add("active");
        }
    }
</script>

And to remove the class you use: .classList.remove("active");

Comments

0

You could do something like this:

var collection = document.getElementsByClassName("hourlyChartPeriod"),
    attr = '';
for (var i = 0; i < collection.length; i++) {
    attr = collection[i].getAttribute("data-period");

    switch (attr) {
        case "days":
            collection[i].style.color = "red";
            break;
        case "week":
            collection[i].style.color = "green";
            break;
        default:
            continue;
    } 
}

Example on JSFiddle


And here is how you can do it with jQuery:

$('.hourlyChartPeriod').each(function() {

    switch ($(this).attr('data-period')) {
        case "days":
            $(this).addClass('red');
            break;
        case "week":
            $(this).addClass('green');
            break;
        default:
            break;
    }

});

Another JSFiddle

You could even just append the data-period name as the CSS class name by changing

$(this).addClass('red'); // change this
$(this).addClass($(this).attr('data-period')); // to this

Although if you can, it would be simpler just to add the class name to begin with.

Comments

0

There is also a very easy way to do that without jQuery:

var active = document.querySelectorAll('[data-period="' + return_value + '"]');

for (var i = 0; i < active.length; i++) {
  active[i].classList.add('active');
}

Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.