How can I make a javascript that sets the background color of an element to the innerhtml color code?

As I’m making a style template for a website, I’d like to make span elements that from example blocks with a background color. Example:

<span class='colblock'>#FF0000</span>

should result in a block with color code #FF0000 (Red) as background color.

Currently, the following css and JS code is being used (relevant bits)
CSS

<style>
    <span.colblock{
        margin:8px;
        padding:8px;
        display:block;
        border:1px solid black;
        border-radius:2px;
        width:66px;
    }
</style>

Javascript (On page bottom, just before body)

<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
    $("colblock").each(function() {
        var ccode = $(this).html();
        $(this).css("background-color", ccode);
    });
</script>

IMO, this is supposed to work, but it does not. Can someone elighten me?


Source: jquery

Leave a Reply