简体   繁体   中英

JavaScript vs jQuery Selector

I was wondering what the difference between jQuery selectors $("#fake-div) and JavaScript selectors getElementById("fake-div") . First, are these even called JavaScript selectors?. I know jQuery returns the jQuery object whereas JavaScript selectors returns the DOM element; however, given these two blocks of code:

jQuery Selector

var post = $("#postid");
var reply_list = post.find(".replies_ul");
var current_reply = document.createElement("li");
current_reply.setAttribute("class", "reply_li");
reply_list.insertBefore(current_reply, reply_list.firstChild);

JS Selector

var content_list = document.getElementById("content_ul");
var current_post = document.createElement("li");
current_post.setAttribute("class","content_li");
content_list.insertBefore(current_post, content_list.firstChild);

The jQuery Selector ends up removing the list from the DOM when the last line of code is called, and the JavaScript selector successfully inserts the list item at the top of the list. I'm looking for an explanation as to what is going on.

The jQuery insertBefore in your code is invalid, it takes two arguments whereas the jQuery accepts only one:

.insertBefore( target )

Description : Insert every element in the set of matched elements before the target.

And the normal one:

Node.insertBefore

Description : Inserts the specified node before a reference element as a child of the current node.

parentElement.insertBefore(newElement, referenceElement)

The difference is not on the selector but on the method / function that you are calling.

You are using the jQuery insertBefore function and comparing it with the javascript insertBefore function.

In jQuery the insertBefore function has only one parameter and therefore you are using it wrong.

If you want to make use of the Javascript function insertBefore instead of the jQuery one, then you have to convert your jQuery object reply_list to a Javascript one. You can do this by using .get(0) or [0] like so:

reply_list[0].insertBefore(current_post, content_list.firstChild);

//or like this
reply_list.get(0).insertBefore(current_post, content_list.firstChild);

In your first block of code, the reply_list is a jQuery object; meaning it doesn't actually have a .firstChild property.

Change it to this:

reply_list.get(0).insertBefore(current_reply, reply_list.get(0).firstChild);

Please note the differences between jQuery's insertBefore and JavaScript's insertBefore

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM