Search code examples
javascriptjquerycssjquery-uijquery-ui-dialog

How to change css properties of html elements using javascript or jquery


How can I change CSS from javascript.

I'm using jQuery-ui Dialog and I want to change the style of a DIV from javascript.

Thanks


Solution

  • Check out the jQuery documentation. If you want anything it will be there.

    Anyhow, if you want to add styles to elements, you need to use the css function, which has a few variants.

    $(selector).css(properties);  // option 1
    $(selector).css(name, value); // option 2
    

    So if you have a DIV with ID of "mydiv" and you want to make the background red, you would do

    $("div#mydiv").css({'background-color' : 'red'}); // option 1
    $("div#mydiv").css('background-color','red');     // option 2
    

    The first way is easier if you're setting multiple things at once.

    If you want to check what a property is currently set to, you would use a variant of the 2nd option, just omit the value.

    var color = $("div#mydiv").css('background-color');
    

    Would make the var color be red if you already set it above, for example.

    You can also add and remove classes, doing something like

    $(selector).addClass(class_name);
    $(selector).removeClass(class_name);