Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

javascript - .appendChild() is not a function when using jQuery

I am trying to transition from pure JavaScript to jQuery. I have a for loop that dynamically creates HTML elements with data from an API. Here is my old code:

recipeDiv = [];
recipeDiv[i] = document.createElement("div"); 
recipeDiv[i].setAttribute("class", "recipeBlock");
recipeDiv[i].appendChild(someElement);

However, when I transitioned to jQuery and used this instead

recipeDiv = [];
recipeDiv[i] = $("<div/>").addClass("recipeBlock");
recipeDiv[i].appendChild(someElement);

I get the following error: recipeDiv[i].appendChild is not a function

I know that .appendChild() isn't jQuery (JS), but shouldn't it still work? Even if I use the jQuery .append() function, I still get an error.

Any help is greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You seem to be confusing yourself by inter-changing jQuery and DOM APIs. They cannot be used interchangeably. document.createElement returns an Element and $("<div />") returns the jQuery object. Element object has the appendChild method and jQuery object has the append method.

As a good practice, I would suggest you choose between DOM APIs or jQuery, and stick to it. Here is a pure jQuery based solution to your problem

var recipeContainer = $("<div/>")
  .addClass("recipeContainer")
  .appendTo("body");

var recipeDiv = [];
var likes = [];

for (var i = 0; i < 20; i++) {

  //Create divs so you get a div for each recipe
  recipeDiv[i] = $("<div/>").addClass("recipeBlock");

  //Create divs to contain number of likes
  likes[i] = $("<div/>")
    .addClass("likes")
    .html("<b>Likes</b>");

  //Append likes blocks to recipe blocks
  recipeDiv[i].append(likes[i]);

  //Append recipe blocks to container
  recipeContainer.append(recipeDiv[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...