JS DOM equivalent for JQuery append - javascript

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>";

Related

jQuery append() vs appendChild()

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.

Raw DOM element vs. jQuery object

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.

jQuery syntax not setting object property

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/

jquery get the html code for all radios/checkboxes within a form

I am trying to parse some elements of a form.
I have with me the form ID/form name.
Now I want to parse through all radio buttons with name= "radio123"(or id="radio123").
But when I try $(this).html on each element (of a radio button)... then I get a blank value...
How do I access the HTML code for all radiobuttons/checkboxes within a form?
This is the normal behavior for jQuery.fn.html function: This method uses the browser's innerHTML property. Look at the examples if you don't understand what I mean.
I don't know why you want to get the HTML (if you want the value, look at the jQuery.fn.val method), but here's a solution
$("input:radio").each(function () {
console.log( this.outerHTML );
});
Be careful with the outerHTML, as it is not supported across all browsers you could use this function:
function getOuterHTML( node ) {
var parent = node.parentNode,
el = document.createElement( parent.tagName ),
shtml;
el.appendChild( node );
shtml = el.innerHTML;
parent.appendChild( node );
return shtml;
}
// use it like getOuterHTML( this ) in the preceding each loop
Something like this should work -
var htmlarr = [];
$("input[type='radio'][name='radio123'],[type='radio'][id='radio123']").each(function () {
//any logic you need here
htmlarr.push($(this).clone().wrap('<div>').parent().html());
})
Demo - http://jsfiddle.net/tJ2Zc/
The code uses this method $(this).clone().wrap('<div>').parent().html() to get the outer HTML of a DOM element. More info can be found in the question - Get selected element's outer HTML
The code above writes all the radio button html into an array but you could change it to do what you wished within the loop.

innerHTML including tags [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I do OuterHTML in firefox?
Could someone show me a method using javascript with which I can get the innerHTML of an element including the tags?
P.S. No jQuery please.
Edit:
Best Method:
function outerHTML(node){
// if IE, Chrome take the internal method otherwise build one
return node.outerHTML || (
function(n){
var div = document.createElement('div'), h;
div.appendChild( n.cloneNode(true) );
h = div.innerHTML;
div = null;
return h;
})(node);
}
Thanks to #Joel below for the solution.
The standard way is just to use the innerHTML property.
document.getElementById("element").innerHTML;
That will get you the full text of all of the HTML inside of the element. To get the element itself you use the outerHTML property.
document.getElementById("element").outerHTML;
I didn't like the posted function so here's something I consider better. Note that IE has different handling of event listeners for the innerHTML and outerHTML properties (that is a general comment, it is not specific to the following), so be careful. There are also differences in the serialisation algorithms so you probably won't get exactly the same inner or outerHTML from all browsers.
The first version below is essentially a more efficient version of the one posted earlier, it uses a better test (in my opinion) for the existence of an outerHTML property and it is more efficient because it doesn't create a new function every time and re-uses the div kept in a closure rather than creating a new one each time. Note that it only does this for browsers that don't have native support for outerHTML, otherwise the temporary div is not kept.
The second version is to be preferred, it is very similar to the above but rather than getting the innerHTML of a clone, it uses the actual node by temporarily replacing it with a shallow clone of itself, moving it to a div, getting the div's innerHTML, then putting it back. The shallow clone is necessary so the temporary replacement maintains a valid DOM (e.g. might be getting the outerHTML of a tr which can only be replaced with a tr).
xLib = {};
xLib.outerHTML = (function() {
var d = document.createElement('div');
// Use native outerHTML if available
if (typeof d.outerHTML == 'string') {
d = null;
return function(el) {
return el.outerHTML;
}
}
// Otherwise, use clone of node and innerHTML
return function(el) {
var html, t = el.cloneNode(true);
// Don't make a new div every time,
// use div in closure
d.appendChild(t);
html = d.innerHTML;
// Remove unwanted fragment
d.removeChild(t);
// Remove reference to fragment
t = null;
return html;
}
}());
xLib.outerHTML2 = (function() {
var d = document.createElement('div');
// Use native outerHTML if available
if (typeof d.outerHTML == 'string') {
d = null;
return function(el) {
return el.outerHTML;
}
}
// Otherwise, use a placeholder and
// remove node, add to temp element,
// get innerHTML and return node to document
return function(el) {
var html;
var d2 = el.cloneNode(false);
// Temporarily move el
el.parentNode.replaceChild(d2, el);
d.appendChild(t);
html = d.innerHTML;
// Put element back
el.parentNode.replaceChild(el, d2);
d2 = null;
return html;
}
}());

Categories

Resources