Altay Mazlum Altay Mazlum - 6 months ago 13
CSS Question

How to change the css of the div that i just created in code

I have the code just below, I don't even know if it works but I just wanted to learn how to change the css properties of the div that I just created within my JQuery structure. Like changing it's width, color and stuff.

<script>
jQuery(document).ready(function () {
jQuery("#button").click(function () {
jQuery("#button").html('Click me again');
jQuery("#button").addClass("button1");
});

jQuery(".button1").click(function () {
jQuery(".button1").hide();
jQuery('<div />')
.addClass('buttondiv')
.css({
'width': '150px',
'height': '150px',
'background-color': 'red'
})
.html(text)
.appendTo("#maindiv");
});
});
</script>


Any help will be appreciated.

Answer

Use css() to add styles to the element.

See the comments inline in the code:

jQuery('<div />') // Create new div element
    .addClass('buttondiv') // Add new class
    .css({ // Add inline styles
        'background-color': 'red',
        'color': 'green'
    })
    .html(text)
    .appendTo("#maindiv"); // No need of `jQuery()` here