Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a div using jquery with style tag

Tags:

html

jquery

tags

I am trying to create a div element using jquery

$(document).ready(function () {
    var ss = {
        id: "foo",
        class: "attack",
        dataa: "hhh",
        style:{
            "color":"red"
        }
    }
    var $div = $("<div>", ss);
    $div.html("dfg");
    $("body").append($div);

It creates the element, but the style object is not adding properly.

Is there a workaround to add style within the tag?

like image 890
balaji g Avatar asked Jan 07 '23 12:01

balaji g


1 Answers

You need to use css not style

$(document).ready(function() {
  var ss = {
    id: "foo",
    class: "attack",
    dataa: "hhh",
    css: {
      "color": "red"
    }
  };
  var $div = $("<div>", ss);
  $div.html("dfg");
  $("body").append($div);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

or you can use style but it should be string as we are setting in style attribute

$(document).ready(function() {
  var ss = {
    id: "foo",
    class: "attack",
    dataa: "hhh",
    style: 'color: red'
  };
  var $div = $("<div>", ss);
  $div.html("dfg");
  $("body").append($div);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
like image 101
Pranav C Balan Avatar answered Jan 24 '23 16:01

Pranav C Balan