Getting element by ID in coffeescript

3.4k views Asked by At

I'm trying to create a HTML widget:

HTML:

<div>
    <h1 class="title" data-bind="title">Title</h1>

    <div>
        <h1 id = "dc1" class="dc">DC1</h1>
    </div>
    <div>
        <h1 id = "dc2" class="dc">DC2</h1>
    </div>

    <p class="updated-at" data-bind="updatedAtMessage"></p>
</div>

And I need to be able to set the background color of the id="dc1" and id="dc2" elements dynamically in CoffeeScript. I plan to do this by adding a class with a background color setting:

SCSS:

&.up {
    background-color: green;
}

&.down {
    background-color: red;
}

.dc {
    background-color: orange;
    font-size: 30px;
    float: left;
    width: 50%;
}

So far I have managed to set the whole widget background but not the child elements mentioned above: I have been using:

CoffeeScript:

$(@node).removeClass('up down')
$('#dc1').removeClass('up down')
$('#dc2').removeClass('up down')

$(@node).addClass('down')
$('#dc1').addClass('down')
$('#dc2').addClass('up')

Note ultimately I will add the classes depending on some data rather than hard coding them to 'up' or 'down' in the coffeescript.

But nothing happends.. Am I getting selecting the id="dc#" elements correctly?

If it helps with context I'm doing this for Dashing

1

There are 1 answers

2
mu is too short On BEST ANSWER

Your SCSS doesn't make sense so I'd guess that your missing an error from the SCSS-to-CSS conversion. An & in SCSS is a reference to the parent selector:

& will be replaced with the parent selector as it appears in the CSS

so have &.up at the top level makes no sense and should generate an error. If we fix the SCSS so that .up and .down apply only to .dc:

.dc {
    /* ... */
    &.up {
        background-color: green;
    }
    &.down {
        background-color: red;
    }
}

then everything seems to work just fine.

Demo: http://jsfiddle.net/ambiguous/9y9uywm9/

You can use Sassmeister (and other similar online tools) to see what SCSS thinks of your original SCSS.