Appending text and classes

super simple for you folks.
Was playing around w/this code.
why can’t i get the newDiv text & class to show? I declared a variable div, appended it to the content div, It shows that there is a new div, but no class or text is added to it.

$(document).ready(function(){

	$("#content").append("<h1> page 1 </h1>").addClass( "content" );
		var newDiv = "<div>";
			$("#content").append(newDiv);
			$(newDiv).addClass( "sCt1" ).append("<p>here is text....</p>");
			

});

Have you tried adding the class and appending the paragraph tag before appending the new div to content? It looks like the query selector for newdiv might lose it’s reference point to that div specifically after being appended.

If you change this I believe it will work

var newDiv = $("<div>");

newDiv was a string, not the element, so you add an empty div to content here

$("#content").append(newDiv);

And then create another element in memory which is never added to content.

$(newDiv).addClass( "sCt1" ).append("<p>here is text....</p>");
1 Like

Makes sense thank you for the explanation.
got this so far


$(document).ready(function(){

	$("#content").append("<h1> page 1 </h1>").addClass( "content" );

    var $newdivs;
    for (i = 0; i < 5; i++) {
        $newdivs = $('<div class="subSect" />').text(i);
        $('#content').append($newdivs);
    }

//but not sure am on the right track w/this bit.

var $countClass;
	
	 for (j = 0; j < 5; j++) {
        $("subSect").attr("class", "subSect"+[j]);
		
		
    }
	
});

Tried this as well. Still no dice. it keeps adding it to the div, rather than to the class name. Also tried replaceWith() and a few other variants.

 $("subSect").each(function(j) {
			 $(this).join(j);
			 j++;
			 });

Closing this. got it.
Thx.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.