Reputation: 205
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.
Upvotes: 0
Views: 1792
Reputation: 11656
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
Upvotes: 1
Reputation: 7522
The jQuery insertBefore
in your code is invalid, it takes two arguments whereas the jQuery accepts only one:
Description: Insert every element in the set of matched elements before the target.
And the normal one:
Description: Inserts the specified node before a reference element as a child of the current node.
parentElement.insertBefore(newElement, referenceElement)
Upvotes: 3
Reputation: 41595
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);
Upvotes: 1