3

Im making some div element dynamically

var QuickPanelItem = $('<div/>', { 'id': 'div' + WidgetDetails.Name + 'QuickPanel', 'class': 'left_slidethumbs button_' + WidgetDetails.Name + '' });            
QuickPanelItem.append($('<div/>', { 'class': 'text_button' }));
$("#divLeftQuickPanel").append(QuickPanelItem);

my doubt is

$('<div/>', { 'class': 'text_button' })

we can add attributes of the element by writting them in the flower brackets as in the above line, But how can we add background-image,margin,padding etc which comes under style property. Also adding inner html.

2
  • .css(), .html() and so on. Commented May 29, 2014 at 12:08
  • $('element').css('margin','20px').css('padding',''); Commented May 29, 2014 at 12:09

3 Answers 3

5

You can do it the exact same way, as jQuery supports any jQuery method in the object passed when creating a new element

$('<div />', { 
    'class': 'text_button',
    css    : {
          backgroundImage : 'url(image.png)',
          margin : '10px 20px 3px 5px'

    },
    html   : '<p>CONTENT</p>',
    on     : {
         click : function() {
            alert();
         }
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Each of the left-hand keys here also have corresponding getter/setter methods, which can be chained and used at any time.
4

You can also do something like this:

js

$("<div/>",{
    id: "a",
    text:"sadsad",
    style:"background-color:red;height:50px;",
    class: "classA"
  }).appendTo("body");

fiddle

Comments

3

Use this .css()

$('#div' + WidgetDetails.Name + 'QuickPanel').css({
    "background-image":"/path",
    "margin":"20px",
    "padding":"4px"
});

1 Comment

Thanks for the answer.I know this way, but I need it in the format I specified in the question,

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.