Jquery add div with class definition

So, I see here add the div and here, how to add the class , but I had problems with combining the two. I want to create a whole bunch of divs of a specific class and id in a sparkLineContainer div.

I have a div div

<div id="#sparkLineContainer"></div>

and I want to add a bunch of the following to it:

    <div id="#sparkLineContainer">
        <div class="sparkLines" id="id1">Some stuff here</div>
        <div class="sparkLines" id="id2">Some stuff here</div>
        <div class="sparkLines" id="id3">Some stuff here</div>
// and so on
    </div>

snippet - I haven't done it very far, I'm at a standstill

$('#sparkContainer').add("div");  \\ How do I add the id and class to this div?
                                  \\ And as a repeat the function will it overwrite this?

The function I'm trying to do this.

function renderSparklines (array1, sparkLineName, id) {
// array1 is the data for the spark line
// sparkLineName is the name of the data.  
// Turn all array values into integers
arrayStringToInt(array1);

    // Create new div of class sparkLines
$('#sparkContainer').add("div")

    // Render new spark line to
$('.sparkLines').sparkline(array1, {width:'90px'});

var htmlString = "";  //  Content to be added to new div
//  GENERATE LITTLE SPARK BOX 
    htmlString += 
                '<font class = "blueDescriptor">' + sparkLineName + '</font>'+
                '<br>'+
                '<font class = "greyDescriptorSmall">Ship to Shore</font>'+
                '<br>'+
                '<font class = "blackDescriptorSparkLine">' + array1[array1.length-1] + '</font>'+
                '<font class = "greenDescriptorSparkline">(' + (array1[array1.length-1] - array1[array1.length-2]) + ')</font>' +
                '<br>';
    $('.sparkLines').prepend(htmlString);

}

+5
source share
4 answers

You need to .appendeither .prependadd a div to the container. See My version below.

var $sparkLines = $('.sparkLines');
$("#sparkLineContainer")
   .append('<div id="id' + 
            ($sparkLines.length + 1) + 
            '" class="sparkLines">Some Stuff Here</div>')

I also noticed that you have an id div like #sparkLineContainer. You should change it as below

<div id="sparkLineContainer"> 
...

Demo

+8
source

add , . append - .

div , :

var $newDiv = $("<div/>")   // creates a div element
                 .attr("id", "someID")  // adds the id
                 .addClass("someClass")   // add a class
                 .html("<div>stuff here</div>");

$("#somecontainer").append($newDiv);
+15

div :

$('<div/>',{ class : 'example'}).appendTo("p");

+2
source

Probably the easiest way is to simply change innerHTML:

$("#sparkLineContainer").append('<div class="sparkLine" id="id1"></div>');

There are other ways, but this is the method that I usually use.

+1
source

All Articles