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?
-
Wow! that was fast. Thanks for the answers. get(0) does indeed return the desired "questionContainer", however, I still have the same problem. The above js works, the jquery does not. Is var currentQnDiv = ... really referencing a div? later code wants to add images to it and then, as shown, currentQnDiv is added to its parent, testDiv.grooble– grooble2012年09月11日 14:14:46 +00:00Commented Sep 11, 2012 at 14:14
-
Got it! Changed it a bit to: var currentQnJQ = (see above), and then, currentQnDiv = currentQnJQ[0]; Thanks all. On my way to reducing a 300 line js file to about 100 jquery, i think...grooble– grooble2012年09月11日 14:20:39 +00:00Commented Sep 11, 2012 at 14:20
5 Answers 5
Use
alert("qndiv class: " + currentQnDiv.get(0).className);
Your currentQnDiv object is a jQuery collection, not a basic Dom object.
Comments
className isn't a valid jQuery property. You should use currentQnDiv[0].className instead
Comments
$("<div/>").addClass("questionContainer")
.attr("qnDiv" + i).appendTo("body");
body Can be replaced with id of element where you want to append this div.
Comments
otherwise
var currentQnDiv = $("<div/>");
currentQnDiv.addClass("questionContainer");
currentQnDiv.attr("qnDiv" + i).appendTo("body");
Comments
Should class really be in "" ?
var currentQnDiv = $("<div/>", {
class: "questionContainer",
id: "qnDiv" + i
});
Just my thought, not enough time to test it myself.