0

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.

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

One more thing... The button that I've added a class does not work after the second click, any thoughts why?
@AltayMazlum You need to use event delegation
@AltayMazlum $(document).on('click', '.buttondiv', function() { ... }); Use this
I did but this time, the button gets hidden even in the first click.
1

http://api.jquery.com/css/

For a single property you can use:

$("#button").css("background-color","yellow");

For multiple style properties:

$("#button").css({"background-color":"yellow", "width":"50px"});

Comments

-1

You can use the jQuery css method in which you can set the css property as following

$(selector).css('width',100);

$(selector).css('color',red);

For more info read the css method of jQuery click here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.