Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    May 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Adding divs to div

    I'm using jQuery to do this, but when I do it, the new div overwrites the old one.

    Code:
    $(document).ready(function(){
    	//find a way to count all of the database rows here
    	var I = 3;
    	var question = 1;
    	function createQdiv(i){
    		question += i;
    		$("#nameTop").append("<div>Blah.</div>").text("something");
    	}
    	for(var i = 0;i< I; i++)
    		createQdiv(i);
    		$(question).text(i);
    	console.log(question);
    	;
    How do I edit the new divs text, using a variable as the text? And any idea how would I keep track of all the new divs?
    Last edited by Emwat_Oon; 06-18-2013 at 03:39 PM.

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,391
    Thanks
    11
    Thanked 568 Times in 561 Posts
    This is the exact reason why the jQuery gods invented two methods

    - $(selectedelement).append(content) will append new content to the selected element. The "result" will be the selected element. So when you use chaining (dot notation), the next method will affect the selected element
    - $(content).appendTo(selectedelement) will create a new element from the content and append it to the selectedelement. The "result" will be the new element. So when you use chaining, the next method will affect the new element
    Code:
    $("<div>Blah.</div>").appendTo("#nameTop").text("something");

  • Users who have thanked devnull69 for this post:

    Emwat_Oon (06-18-2013)

  • #3
    New to the CF scene
    Join Date
    May 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Another question, because I'm doing things a long and unnecessary way, but is there a way to simplify this? I have all these variables. I'm going to replace I with however long the database is.

    Code:
    $(document).ready(function(){
    	//find a way to count all of the database rows here
    	var I = 3;
    	var question = 0;
    	var newDiv = "<div></div>";
    	var whyDoThis = "question";
    	var classDiv;
    	function createQdiv(i){
    		question = i;
    		classDiv = whyDoThis.concat(i);
    		$(newDiv).appendTo("#nameTop").addClass(classDiv).text(question);
    	}
    	for(var i = 0;i< I; i++)
    		createQdiv(i);
    	console.log(question);
    	;


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •