grooble
grooble

Reputation: 657

constructing dynamic divs in jquery and javascript

Hmmm All the answers I've seen here suggest that this should work, but...

Is...

    var qnDivName = "qnDiv" + i;
    var currentQnDiv = document.createElement("div");
    var qnDivId = document.createAttribute("id");
    qnDivId.nodeValue = qnDivName;
    currentQnDiv.setAttributeNode(qnDivId);
    currentQnDiv.className = "questionContainer";

equivalent to...

    var currentQnDiv = $("<div/>", {
        "class": "questionContainer",
        id: "qnDiv" + i
    });
    alert("qndiv class: " + currentQnDiv.className);

?

The alert gives 'undefined'. The 'i' is from a for loop. I'm dynamically creating divs to attach to a document further down the page...

    testDiv.appendChild(currentQnDiv);      
  } //end for loop

the ordinary js works, but the jQuery doesn't. I have other jQuery that works in a calling function, so...

Any ideas?

Upvotes: 1

Views: 66

Answers (5)

Patriks
Patriks

Reputation: 1012

otherwise

var currentQnDiv = $("<div/>");
currentQnDiv.addClass("questionContainer");
currentQnDiv.attr("qnDiv" + i).appendTo("body");

Upvotes: 1

Patriks
Patriks

Reputation: 1012

$("<div/>").addClass("questionContainer")
           .attr("qnDiv" + i).appendTo("body");

body Can be replaced with id of element where you want to append this div.

Upvotes: 1

Niels Thiebosch
Niels Thiebosch

Reputation: 147

Should class really be in "" ?

var currentQnDiv = $("<div/>", {
    class: "questionContainer",
    id: "qnDiv" + i
});

Just my thought, not enough time to test it myself.

Upvotes: 0

Simon
Simon

Reputation: 2830

className isn't a valid jQuery property. You should use currentQnDiv[0].className instead

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

Use

alert("qndiv class: " + currentQnDiv.get(0).className);

Your currentQnDiv object is a jQuery collection, not a basic Dom object.

Upvotes: 2

Related Questions