1

I'm trying to change the class of a div if that div's id is less than the value of my var. This is my first time asking a question and my first time using jQuery so I sure this is embarrassingly easy, but I couldn't find the answer anywhere. Here is the code I am currently using:

$(function(){
var today = new Date(); 
var weekno = today.getWeek()-1;
$("div[id$<weekno]").addClass("hidden");
})

Thanks!

4 Answers4

0

LIVE DEMO

$(function(){

    Date.prototype.getWeek = function() {
        var FY = new Date(this.getFullYear(),0,1);
        return Math.ceil((((this - FY) / 86400000) + FY.getDay()+1) / 7);
    };

    var weekno = new Date().getWeek();

  //alert(weekno);
    $("div").each(function(){
       var weekNum = this.id.match(/\d+/);
       if(weekNum  && weekNum < weekno){
           $(this).addClass("hidden");
       }
    });

});
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

I don't think JavaScript has a method for getting the week number, so your first problem would be to find a way of calculating it. I would start by having a look at the code here

Following that, you should look into HTML id values. Just using an integer is not valid, so you should figure out a way of incorporating the number somewhere after a string.

Your next place to look would be at CSS selectors. Conditionals for a less than in a selector is not valid, so you would probably have to iterate through each one (check out jQuery each) here.

I came up with a quick soluiton to your problem here: http://jsfiddle.net/vpgNL/

HTML:

<div class="week" id="week_2">Week 2</div>
<div class="week" id="week_5">Week 5</div>
<div class="week" id="week_11">Week 11</div>

JavaScript:

$(function(){
    var today = new Date(); 
    var weekno = 10;
    $(".week").each(function() {
        n = $(this).attr("id").split("_")[1];
        if(n < weekno) {
            $(this).hide();
        }
    });
});

Hope this helps.

Community
  • 1
  • 1
tpbowden
  • 2,040
  • 15
  • 22
0

Here is an example to of how do exactly as described: http://jsfiddle.net/SinisterSystems/yJ4cu/2/

HTML:

<div id="1">Hello world</div>
<div id="2">Hello world2</div>
<div id="15">Hello world2</div>

CSS:

.foo {
    font-size:100px;
}

jQuery:

$(function(){
    $( "div" ).each(function( index ) {
        if($(this).attr('id') < 10){
            $(this).addClass('foo');
        }
    });
});

So, what we're doing here with the JS:

$( "div" ).each(function( index ) { // Find every div
    if($(this).attr('id') < 10){    // if it has an ID of under x
        $(this).addClass('foo');    // add the class
    }
});
Boaz
  • 19,892
  • 8
  • 62
  • 70
Nicholas Hazel
  • 3,758
  • 1
  • 22
  • 34
-1

First, Date object has no getWeek() method, Second, Do you want to use id attribute selector? You can try this:

$("div[id$" + weekno + "]").addClass("hidden");

or you can jQuery

cookfront
  • 1
  • 1