Search code examples
jquerycssprepend

Add .css() to prepended div


This prepend function adds a div with the "colorBox" class, but I'm having trouble setting the css for the newly created div. I don't know if my syntax is quite right, but I'm trying to use the data-background value in the parent (li) tag.

I'm using this to add color boxes to multiselect options, and the plugin that I'm using converts each option into a <li> that is structured like the HTML I've included below.

JS

$(function(){
    $("li span").prepend('<div class="colorBox"></div>').css('background-color', $(this).parent().attr("data-background"));   
});

HTML

<ul>
    <li data-background="#C11B17">
        <input type="checkbox" name="color[]" value="Brick_Red">
        <span>Brick Red</span>
    </li>
</ul>

Solution

  • Try splitting your code up a bit. It's failing because .css() is actually being called on the parent and this is referring to window in your context.

    jsFiddle

    $(function(){
        // Get all elements matching selector 'li span'
        var spans = $("li span");
        // Loop for each element in spans
        spans.each(function () {
            // Create the new element as a jQuery object
            var elem = $('<div class="colorBox">test</div>');
            // Set the new element's background-color to the attribute on the parent
            // of the span
            elem.css('background-color', $(this).parent().attr("data-background"));
            // Prepend the new element to the span (insert it as the first child)
            $(this).prepend(elem);
        });
    });
    

    If you mean to wrap "Brick Red" in the div then you will need to use .wrap() or .wrapInner().

    jsFiddle

    $(this).wrap(elem);
    

    Update

    If you're after custom checkboxes, I suggest a more css-driven approach which takes advantage of the <label> tag.

    jsFiddle

    HTML

    <ul>
        <li data-background="#C11B17">
            <input type="checkbox" name="color[]" value="Brick_Red" id="checkbox1" />
            <label for="checkbox1">
                <span>Brick Red</span>
            </label>
        </li>
    </ul>
    

    CSS

    input[type=checkbox] {
        display:none;
    }
    
    input[type=checkbox] + label:before {
        display:inline-block;
        content:"";
        width:1em;
        height:1em;
        background-color:#CCC;
    }
    
    input[type=checkbox]:checked + label:before {
        background-color:#C11B17;
    }
    

    Note that this method will work in IE8+ without any polyfills.