$fn.insertAfter() and $fn.after() Jquery - javascript

I understand that $fn.insertAfter() is used to insert element after the element supplied as the argument. How's $fn.after() different from it?

$.fn.after()help inserts an element after the target element, on which you call it.
$('div').after('<div>new div</div>');
whereas, $.fn.insertAfter inserts the target element after the node you specify:
$('<div>new div</div>').insertAfter($('#someid'));
The latter is mostly prefered, because you keep a reference to the newly created element and can chain more methods on it. So for instance:
$('<div>new div</div>')
.insertAfter($('#someid'))
.attr('foo', 'bar')
.css({
'background-color': 'red'
});
is possible. You cannot do that with .after()help. The same thing is for .append()help / .appendTo()help and .insertBefore()help / .before()help

This is an example of the same thing, the difference is the context of the selector. insertAfter inserts the selected element after the parameter
after inserts the parameter after the selected element.
$('<div id="foo"></div>').insertAfter('#bar');
$('#bar').after('<div id="foo"></div>');

Quoting straight from the documentation:
The .after() and .insertAfter()
methods perform the same task. The
major difference is in the
syntax—specifically, in the placement
of the content and target. With
.after(), the selector expression
preceding the method is the container
after which the content is inserted.
With .insertAfter(), on the other
hand, the content precedes the method,
either as a selector expression or as
markup created on the fly, and it is
inserted after the target container.

This mentions that they perform the same task but have different syntax.

Related

Nightmare Testing click() selector

I want to get a reference to a DOM element and click on it but I don't know how to spot it.
In DOM will be like:
$('.filter-buttons :nth-child(2)').get(0).click() , or using [0]instead of get(0)
But with Nightmare function click accepts only one parameter .click(selector)
.click('.filter-buttons :nth-child(2)')
. The question is that I don't know where to put the get(0). Any ideas?
As it has mentioned .get(0) lets you find a dom node and you are applying a dom click event. so i suggest you to use document.querySelector() method:
.click(document.querySelector('.filter-buttons :nth-child(2)'))
document.querySelector():
This method just returns a single dom node. which exactly is your requirement.
from the docs:
Returns the first element within the document (using depth-first pre-order traversal of the document's nodes|by first element in document markup and iterating through sequential nodes by order of amount of child nodes) that matches the specified group of selectors.
Example
In this example, the first element in the document with the class "myclass" is returned:
var el = document.querySelector(".myclass");

How to append to a variable in jquery?

I have the following code:
var golden_site = '<div id="golden_site"></div>';
$('.form_content').append(golden_site);
var lookup = '<input type="text" name="lookup" value="test">';
Why is this not working:
$(golden_site).append(lookup);
But accessing the node by id works:
$('#golden_site').append(lookup);
This $('#golden_site') selects the div with id=golden_site. While this $(golden_site) doesn't select anything.
Taken from here, you have the following ways of selecting an element using jQuery
Selecting Elements by ID
Selecting Elements by Class Name
Selecting Elements by Attribute
Selecting Elements by Compound CSS Selector
Pseudo-Selectors
The way you tried to select your div doesn't follow one of the above ways. Hence you didn't make it. While using the id you made it, since this is included in the above ways.
update
As Guffa pointed out (I didn't now it) in his comment,
The call $(golden_site) doesn't try to use the string as a selector at
all. It will create an elements from the HTML string, and actually
return that element
The code is working fine, but it doesn't do what you think.
The $(golden_site) part will create a new div element from the HTML code in the string. The lookup element will then be appended to that div. As the div is an element that you just created, it's not in the page and the lookup element that you appended to it isn't in the page either.
If you create the div element first and then append that to the page, instead of using a string in the append, then you have a reference to the div element:
var golden_site = '<div id="golden_site"></div>';
var element = $(golden_site);
$('.form_content').append(element);
Now you can append things to it:
element.append(lookup);
Because when you say
$(golden_site).append(lookup);
Actually you mean:
'<div id="golden_site"></div>'
In plain words, it's just a string, not a jQuery object that can be appended to. golden_site is just a string.
The reason is because the $() is in fact a wrapper of jQuery over the document.querySelector(). So as expected both methods should behave similar, when you do:
$("#blah").append(x);
Indeed the browser is doing this:
document.querySelector("#blah").appendChild(x);
So both methods should work as they explain here -> How query Selector works
As you can see the variable passed as argument is a string that will be used as a CSS Selector, they explain here -> CSS Selector List
I will add this graphic with some of the most common ways to select elements from the DOM, don't forget the '', courtesy from W3CSchools.

Does "this" keyword return the DOM element

I have a task where I need to move elements with classname clearOnHover on click to another "div" element with classname sortingContainer. For that I wrote the following code.
$("body").on('click','.clearOnHover',function(){
$('.sortingContainer').append(this);
});
"this" variable removed the tags with classname "clearOnHover" from its original place in DOM and appended it to "sortingConatiner" div.
Can you help me understand why the element was removed from the DOM, and what exactly caused it.?
http://jsfiddle.net/NMWwL/1/
append() will always remove the DOM element from it's original position. If you need to copy it, use clone() instead.
From the jquery docs :
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned)

jQuery: Add Sibling of Parent to Current Matched Elements

I'm trying to - in one line - remove the parent element of a clicked element and the parent's lone sibling element. This is my two-liner solution here:
$(document).ready(function() {
$('.close').click(function() {
$(this).parent().siblings('.sibling').remove();
$(this).parent().remove();
});
});
Here's a working fiddle. I'm looking to avoid navigating the DOM twice since I've already found the parent of the clicked element when I remove the sibling, there's no reason I should be doing it again. I'm aware that I could wrap both the parent and sibling in an element and just remove that super element, but at this point I'd like to avoid that as well.
I've looked into using jQuery's .add() function, but I can't seem to get that to work. Thanks for your help!
You're looking for .addBack():
$(this).parent().siblings('.sibling').addBack().remove();
Demo
andSelf is an equivalent to .addBack() for jQuery < 1.8
With .add(), you would have to store the parent in a variable to avoid traversing to it twice:
var $father = $(this).parent();
$father.siblings('.sibling').add($father).remove();
//one-liner without storing in a variable would traverse the DOM twice:
$(this).parent().siblings('.sibling').add($(this).parent()).remove();
As you can see, the addBack method is more practical in this case.
In case the element's parent and the parent's sibling are the only elements inside their parent, you can also use:
$(this.parentNode.parentNode).empty();
Demo
The native parentNode property is a bit faster than jQuery's .parent() method. It is up to which to use.
Note that such small traversing has very little overhead either way. Your original code and these versions have very little difference performance-wise.

creating an element in jquery

So, I know how to create an element in jQuery in various ways. But I've never come across this before today:
var myspacer = $('<div />', {
"id": "nav-spacer",
"height": mynav.outerHeight()
});
Later on in the code, this variable is added to the DOM with jQuery's .before() method. Can somebody explain what's going on here? What kind of object is being created? How does jQuery know how to turn this into an HTML element?
That is the $( html, props ) syntax of the jQuery() function - it is explained quite clearly in the API documentation:
html A string defining a single, standalone, HTML element (e.g. <div/> or <div></div>).
props An map of attributes, events, and methods to call on the newly-created element.
If the function determines that the first parameter is a string that looks like an html snippet it creates a new element (or elements) from that snippet. If you pass a map in the second parameter it creates the specified attributes on the newly created element.
The new element is not automatically added to the document, but you seem to already have seen that since you mention the .before() code that does add it.
According to jQuery $( html, properties) syntax, above code creating a div with id="nav-spacer" and height supplied by mynav.outerHeight() method without any content as jQuery object but not added to DOM.
In $( html, properties), html is string and properties is collection of attributes/event and so on.
An alternative approach may be:
var myspacer = $('<div id="nav-spacer" height="'+ mynav.outerHeight() +'"></div>');
But your one is more readable and efficient.
Using .before() method myspacer is added to DOM just before the selector passed within .before() as param. Example:
myspacer.before('div.hello');
Will add myspacer before the div with class=hello like:
<div id="nav-spacer" height="some_value"></div>
<div class="hello"></div>
jQuery creates a new element if you pass in HTML like $('<div/>') because it's smart. :P It recognizes that the string is HTML (rather than a selector) and treats it differently. See the docs.
The new element is created but not added to the DOM until you add it yourself, eg. with appendTo().
From the documentation: "To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag."
Edit: I stand corrected, you can write $('<div/>') without an explicit closing tag. This works as long as the HTML doesn't contain nested elements (of course). See the other examples from the docs:
// With nested elements and closing tags - HTML must be well formed
$("<div><p>Hello</p></div>").appendTo("body");
// Without closing tag - HTML is still well formed
$("<div/>", {
"class": "test",
text: "Click me!",
click: function(){
$(this).toggleClass("test");
}
}).appendTo("body");
Similar questions:
jQuery document.createElement equivalent?
Creating a div element in jQuery
What is the most efficient way to create HTML elements using jQuery?
http://api.jquery.com/jQuery/#jQuery2
This should give you the explanation you're looking for =D.
To summarize, it's a quick JQuery on-the-fly element creation method.

Categories

Resources