I'm looking at the following example of explicit iteration from http://jqfundamentals.com/chapter/jquery-basics:
$( 'li' ).each(function( index, elem ) {
// this: the current, raw DOM element
// index: the current element's index in the selection
// elem: the current, raw DOM element (same as this)
$( elem ).prepend( '<b>' + index + ': </b>' );
});
The comments refer to elem as a raw DOM element, but then the code calls .prepend() on elem.
I'm just getting started with jQuery, but it's my understanding you can only call a jQuery method on a jQuery object - not on a raw DOM element. Am I misunderstanding?
The code does not call prepend on elem, it calls it on $(elem) making it a jquery object.
elem is a raw DOM element. By wrapping elem $(elem) you are creating a jQuery object from the raw DOM element. jQuery allows you to do this. You are then calling .prepend() on the jQuery object created from elem.
This could be helpfull..
var test = document.getElementById('test') //returns a HTML DOM Object
var test = $('#test') //returns a jQuery Object
var test = $('#test')[0] //returns a HTML DOM Object
you are converting the raw DOM element to jquery object again.. see the first $ sign in the the elem. elem is raw but $(elem) is jquery object and thus you can use any jQuery function(methods) available prepend being one
$( elem ).prepend( '<b>' + index + ': </b>' );
//-^-- here this $ sign
The "elem" in the example above could be any tag (h1, p, body, a combination of tags, a specific reference to an id or class) Just like CSS. Then "prepend" is the action performed on that element. In this case the prepend action take one parameter, which is another element that will be dynamically placed into the html as the first child element for every element on the page that matches your selected "elem"
jQuery creates a "wrapped" element - a jQuery object
so perhaps this will give your some insight:
$('li').each(function (index, elem) {
alert(elem === this); // true
alert($(this) === $(elem)); // false
alert(elem.tagName + $(elem).tagName); // LI undefined
alert(typeof elem + typeof $(this));// object object
alert(elem.tagName === $(this).prop('tagName')); // true
});
Notice that second alert = false, so even though they "refer" to the same element, $(this) and $(elem) are NOT the same wrapped object. Notice that the "raw" elem has a .tagName whereas the jQuery wrapped object does not.
SO for your
$(elem).prepend('<b>' + index + ':</b>');
jquery takes the wrapped elem ($(elem)), and then prepends a NEW wrapped 'b' element with the index and ":" character as its content text
EDIT: added example of the property for tagName to the jQuery object in a further example and a prepend explanation.
Unlike Prototype, jQuery doesn't extend native objects. This is why you have to use $ function to get jQuery-wrapped one.
Related
I have written a small JS to iterate through a set of matched elements and perform some task on each of them.
Here is the code:
var eachProduct = $(".item");
eachProduct.each(function(index, element){
var eachProductContent = element.find(".product-meta").clone();
});
When I console log element it outputs properly and the exact objects. Why should jquery throw this error?
because element is a dom element not a jQuery object
var eachProductContent = $(element).find(".product-meta").clone();
Inside the each() handler you will get the dom element reference as the second parameter, not a jQuery object reference. So if you want to access any jQuery methods on the element then you need to get the elements jQuery wrapper object.
You are calling .find() on a plain JS object, But that function belongs to Jquery object
var eachProductContent = $(element).find(".product-meta").clone();
You can convert it to a jquery object by wrapping it inside $(). And in order to avoid this kind of discrepancies you can simply use $(this) reference instead of using other.
Use $(this) for current Element
var eachProductContent = $(this).find(".product-meta").clone();
you should change "element" to "this":
var eachProduct = $(".item");
eachProduct.each(function(index, element){
var eachProductContent = $(this).find(".product-meta").clone();
});
Here's some sample code:
function addTextNode(){
var newtext = document.createTextNode(" Some text added dynamically. ");
var para = document.getElementById("p1");
para.appendChild(newtext);
$("#p1").append("HI");
}
<div style="border: 1px solid red">
<p id="p1">First line of paragraph.<br /></p>
</div>
What is the difference between append() and appendChild()?
Any real time scenarios?
The main difference is that appendChild is a DOM method and append is a jQuery method. The second one uses the first as you can see on jQuery source code
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.appendChild( elem );
}
});
},
If you're using jQuery library on your project, you'll be safe always using append when adding elements to the page.
No longer
now append is a method in JavaScript
MDN documentation on append method
Quoting MDN
The ParentNode.append method inserts a set of Node objects or DOMString objects after the last child of the ParentNode. DOMString objects are inserted as equivalent Text nodes.
This is not supported by IE and Edge but supported by Chrome(54+), Firefox(49+) and Opera(39+).
The JavaScript's append is similar to jQuery's append.
You can pass multiple arguments.
var elm = document.getElementById('div1');
elm.append(document.createElement('p'),document.createElement('span'),document.createElement('div'));
console.log(elm.innerHTML);
<div id="div1"></div>
append is a jQuery method to append some content or HTML to an element.
$('#example').append('Some text or HTML');
appendChild is a pure DOM method for adding a child element.
document.getElementById('example').appendChild(newElement);
I know this is an old and answered question and I'm not looking for votes I just want to add an extra little thing that I think might help newcomers.
yes appendChild is a DOM method and append is JQuery method but practically the key difference is that appendChild takes a node as a parameter by that I mean if you want to add an empty paragraph to the DOM you need to create that p element first
var p = document.createElement('p')
then you can add it to the DOM whereas JQuery append creates that node for you and adds it to the DOM right away whether it's a text element or an html element
or a combination!
$('p').append('<span> I have been appended </span>');
appendChild is a DOM vanilla-js function.
append is a jQuery function.
They each have their own quirks.
The JavaScript appendchild method can be use to append an item to another element. The jQuery Append element does the same work but certainly in less number of lines:
Let us take an example to Append an item in a list:
a) With JavaScript
var n= document.createElement("LI"); // Create a <li> node
var tn = document.createTextNode("JavaScript"); // Create a text node
n.appendChild(tn); // Append the text to <li>
document.getElementById("myList").appendChild(n);
b) With jQuery
$("#myList").append("<li>jQuery</li>")
appendChild is a pure javascript method where as append is a jQuery method.
I thought there is some confusion here so I'm going to clarify it.
Both 'append' and 'appendChild' are now native Javascript functions and can be used concurrently.
For example:
let parent_div = document.querySelector('.hobbies');
let list_item = document.createElement('li');
list_item.style.color = 'red';
list_item.innerText = "Javascript added me here"
//running either one of these functions yield same result
const append_element = parent_div.append(list_item);
const append_child_element = parent_div.appendChild(list_item);
However, the key difference is the return value
e.g
console.log(append_element) //returns undefined
whereas,
console.log(append_child_element) // returns 'li' node
Hence, the return value of append_child method can be used to store it in a variable and use it later, whereas, append is use and throw (anonymous) function by nature.
Below is the code where I obtain my input element with jQuery:
var txt = $(tableRow).find('input:text');
if (txt.value == null) {
//TO DO code
}
and here's how I do it with pure JavaScript
var txt = document.getElementById('txtAge');
if (txt.value == null) {
//TO DO code
}
With the first way the value of the txt is undefined. But with the second way the value is what's inside the input element. Now more interesting is, on the bottom-right pane of the Mozilla Firebug if I scroll down to the "value" of the txt I can see it there, both ways.
I know I can simply say $(txt).val(), but I also want to understand why I can't access the value of an element if it's been selected by jQuery. Isn't jQuery just a library of JavaScript functions?
.value is not part of the jquery api. You should use .val() instead:
var txt = $(tableRow).find('input:text');
if (txt.val() == "") {
//TO DO code
}
A dom object and a jquery dom object are not exactly the same. In fact, you can open the Developer tools (in webkit) or Firebug (Firefox) to check what are they in the inside. Jquery holds more information (actually, it contains an instance of the dom that it's representing). So, if you wanted to use .value, you need to call the "generic" dom object from the jquery object, and then use .value.
jQuery selects DOM elements using various native and non-native techniques and places them all in it’s own array-like instance that also wraps them in their own API. jQuery doesn’t "extend" native DOM properties or methods, so you will need to target the DOM node to do that.
Think of it like this:
var node = document.getElementById('txtAge'); // the DOM node
var txt = $('#txtAge'); // the same node wrapped in a jQuery object/API
Since jQuery object holds an array-like collection of DOM nodes, so you can access the first element by doing:
txt[0] // same as node
But it’s generally recommended that you use the .get() method:
txt.get(0)
Another more jQuery-way to do what you want is to iterate through a jQuery collection using .each():
$(tableRow).find('input:text').each(function() {
// "this" in the each callback is the DOM node
if ( this.value == null ) {
// Do something
}
});
.find() will return an arry-like object. If you're sure that there's one, and one only, element matching your query, you could do
var txt = $(tableRow).find('input:text')[0].value;
That's not very jQuery-like, so to speak, more like a mismatch of both jQuery and DOM methods, but it'll get what you want. Also, since you show, as a DOM example, var txt = document.getElementById('txtAge');, this could be rewritten in jQuery as
var txt = $('#txtAge')[0];
var x = $(tableRow).find('input:text');
It's an jquery object .
`x.value`
There is no property value in jquery object . So it returns undefined.
x.val() is a method you can use for get the value of an element.
My jQuery question I beleive is pretty simple, which is driving me insane that I can't get it.
I have an object with a property "content", I want to be able to take that object, manipulate the property "content" with jQuery and then overwrite the value with the new value jQuery creates.
Example:
o.content = "<div><span>hello</span></div>";
$('div', o.content).addClass('test');
At this point I want o.content to be equal to <div class='test'><span>hello</span></div>
I can not for the life of me figure out the syntax. Any help is really appreciated.
This will give you a string <div class="test"><span>hello</span></div> if this is what you want:
$(o.content).addClass('test').wrap('<div>').parent().html();
Parse the html in o.content, add the class, append the parsed html to a new <div>, and get the html of the new div:
o.content = "<div><span>hello</span></div>";
var el = $(o.content).addClass('test');
o.content = $("<div>").append(el).html();
Edit: This assumes you want o.content to still contain a string, rather than a jQuery object. In that case, it's simpler:
o.content = $(o.content).addClass('test');
from the docs of the jquery function, context must be
A DOM Element, Document, or jQuery to use as context
Your context (o.content) is a string. Also, the jQuery function is not able to select the entire context, it can only select elements in that context.
Try this instead:
// make o.content a jquery element, not a string
o.content = $("<div><span>hello</span></div>");
// select on something inside the context (inside the div), not the div itself
$('span', o.content).addClass('test');
http://jsfiddle.net/JfW4Q/
I don't think you can lookup an element from a string like that.. I would rather do it like below,
var content = "<span>hello</span>";
content = $('<div/>', {class: 'test'}).html(content)
DEMO: http://jsfiddle.net/k4e5z/
You want the following
o.content = "<div><span>hello</span></div>";
// Create a jQuery object you can call addClass on
var docFragment = $(o.content);
docFragment.addClass('test');
// Since there's no outerHTML in jQuery, append it to another node
var wrapper = $('div');
docFragment.appendTo(wrapper);
// The HTML of the wrapper is the outerHTML of docFragment
console.log(wrapper.html()); // outputs <div class='test'><span>hello</span></div>
Why not do it all in one line:
var o = {};
o.content = $( "<div></div>" ) // create element
.addClass('test') // add class
.html( '<span>hello</span>' ); // append content
Fiddle: http://jsfiddle.net/kboucher/eQmar/
o.content = $("<div><span>hello</span></div>");
o.content.addClass('test');
o.content is a jQuery object in this example, as opposed to just a string. Here's a demo on jsfiddle: http://jsfiddle.net/cvbsm/1/
What is the standard DOM equivalent for JQuery
element.append("<ul><li><a href='url'></li></ul>")?
I think you have to extend the innerHTML property to do this
element[0].innerHTML += "<ul><li><a href='url'></a></li></ul>";
some explanation:
[0] needed because element is a collection
+= extend the innerHTML and do not overwrite
closing </a> needed as some browsers only allow valid html to be set to innerHTML
Hint:
As #dontdownvoteme mentioned this will of course only target the first node of the collection element. But as is the nature of jQuery the collection could contain more entries
Proper and easiest way to replicate JQuery append method in pure JavaScript is with "insertAdjacentHTML"
var this_div = document.getElementById('your_element_id');
this_div.insertAdjacentHTML('beforeend','<b>Any Content</b>');
More Info - MDN insertAdjacentHTML
Use DOM manipulations, not HTML:
let element = document.getElementById('element');
let list = element.appendChild(document.createElement('ul'));
let item = list.appendChild(document.createElement('li'));
let link = item.appendChild(document.createElement('a'));
link.href = 'https://example.com/';
link.textContent = 'Hello, world';
<div id="element"></div>
This has the important advantage of not recreating the nodes of existing content, which would remove any event listeners attached to them, for example.
from the jQuery source code:
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem ); //<====
}
});
},
Note that in order to make it work you need to construct the DOM element from the string, it's being done with jQuery domManip function.
jQuery 1.7.2 source code
element.innerHTML += "<ul><li><a href='url'></li></ul>";