Why is insertAdjacentHTML converting HTML into an object - javascript

Compiling a directive for injection but inserting it into the DOM is not working. Any ideas?
_testHeader = $compile(ABHeaderTemplate)($scope);
_testHeader now equals [<header class="ng-scope">..</header>]
Grab the index so it's not an array.
_testHeader[0] returns <header class="ng-scope">..</header>
Then trying to insert it into DOM
document.body.children[0].insertAdjacentHTML("afterbegin", _testHeader[0]);
returns "[object HTMLElement]"
I've tried using append (to no avail) and I'm compiling the template on load and triggering the appending through an event. Not sure what's going on.

insertAdjacentHTML inserts HTML string. You need appendChild or in your case insertBefore since you want to prepend new content into body:
document.body.insertBefore(_testHeader[0], document.body.children[0]);

Related

What is the difference between insertAdjacentHtml and insertAdjacentElement?

What is the main difference between element and html?
I used
insertAdjacentElement('beforeend', html);
and it showed error. But worked when using
insertAdjacentHTML('beforeend', html);
Just wondering what the difference was.
insertAdjacentElement() is used to insert an element which is already in the Dom.
You can get this element with getElementById() for example.
https://www.w3schools.com/jsref/met_node_insertadjacentelement.asp
insertAdjacentHtml() is used to insert html code.
https://www.w3schools.com/jsref/met_node_insertadjacenthtml.asp
The insertAdjacentElement method is only compatible with either elements already present in the DOM or new elements created with document.createElement method.
The insertAdjacentHTML however will not work when you are trying to insert DOM elements into another but rather works on strings that can be parsed as XML or HTML which is then added to the parent container.
Although they are pretty similar in that they have more positioning parameters than node.appendchild and element.append methods

JS: Moving an anchor with insertAdjacentHTML only appends the href, not the element

I'm trying to move an anchor tag from one element to another. When I do this, the only thing appended is the anchors href, not the element itself. Why is this and how can I fix it?
I need a solution in Javascript only as jQuery isn't being used
Thanks for any help!
Fidde: https://jsfiddle.net/p7g7mkxs/
What I've tried:
<p class="hello">hello</p>
<p class="hello">helloLINK</p>
var hello = document.querySelectorAll('.hello');
hello[0].insertAdjacentHTML('beforeEnd', hello[1].querySelectorAll('a')[0]);
I've also tried using different variations of selecting my elements, like getElementsByTagName or appending it differently with innerHTML - Everything I've tried has given me the same result.
You use insertAdjacentHTML with HTML (a string), not with an actual element. If you pass it an element, the element is converted to string (like String(theElement)). In the case of an HTMLAnchorElement, that means you just get the href. Proof:
console.log(
String(document.querySelector("a"))
);
Hey
To append an element to the end of another element's child list, use appendChild:
var hello = document.querySelectorAll('.hello');
hello[0].appendChild(hello[1].querySelector('a'));
(To insert it elsewhere, use insertBefore. Actually, you can use insertBefore in all cases if you like, just use null as the reference element when adding to the end.)
Also note that when you only want the first match, rather than querySelectorAll(/*...*/)[0], use querySelector(/*...*/), which returns the first match or null.
In addition to what #t-j-crowder said, you can also use outerHTML to accomplish the task:
var hello = document.querySelectorAll('.hello');
hello[0].insertAdjacentHTML('beforeEnd', hello[1].querySelectorAll('a')[0].outerHTML);

What is the difference between appendChild, insertAdjacentHTML, and innerHTML

I want to know what the difference is between appendChild, insertAdjacentHTML, and innerHTML.
I think their functionality are similar but I want to understand clearly in term of usage and not the execution speed.
For example, I can use innerHTML to insert a new tag or text into another tag in HTML but it replaces the current content in that tag instead of appends.
If I would like to do it that way (not replace) I need to use insertAdjacentHTML and I can manage where I want to insert a new element (beforebegin, afterbegin, beforeend, afterend)
And the last if I want to create (not insertion in current tag) a new tag and insert it into HTML I need to use appendChild.
Am I understanding it correctly? Or are there any difference between those three?
element.innerHTML
From MDN:
innerHTML sets or gets the HTML syntax describing the element's descendants.
when writing to innerHTML, it will overwrite the content of the source element. That means the HTML has to be loaded and re-parsed. This is not very efficient especially when using inside loops.
node.appendChild
From MDN:
Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.
This method is supported by all browsers and is a much cleaner way of inserting nodes, text, data, etc. into the DOM.
element.insertAdjacentHTML
From MDN:
parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. [ ... ]
This method is also supported by all browsers.
....
The appendChild methods adds an element to the DOM.
The innerHTML property and insertAdjacentHTML method takes a string instead of an element, so they have to parse the string and create elements from it, before they can be put into the DOM.
The innerHTML property can be used both for getting and setting the HTML code for the content of an element.
#Guffa did explain the main difference ie innerHTML and insertAdjacentHTML need to parse the string before adding to DOM.
In addition see this jsPerf that will tell you that generally appendChild is faster for the job it provides.
One that I know innerHTML can grab 'inner html', appendChild and insertAdjacentHTML can't;
example:
<div id="example"><p>this is paragraph</p><div>
js:
var foo = document.getElementById('example').innerHTML;
end then now
foo = '<p>this is paragraph</p>';
DOCS:
appendChild
insertAdjacentHTML
innerHtml
innerHTML vs appendChild() performance
insertAdjacentHTML vs innerHTML vs appendChild performance
the main difference is location (positioning) :
(elVar mean element saved to variable)
** elVar.innerHTML: used to sets/get text and tags (like ) inside an element (if u use "=" it replace the content and "+=" will add to the end.
** divElvar.appendChild(imgElVar): to add pure element to the end of another element (or start with prepend) .
** insertedElVar.insertAdjacentElement(beforebegin,targetElvar): it insert element into spicific location before elVar (after it with "afterend").
-innerText: can replace/get/insertOnEnd text.but can read tags and text inside element with display:hidden , cant insert on start .
-innercontent : show all text inc hidden , cant read html tags and it put empty spaces instead of them , cant insert on start
-innerHTML: read all set all , cant insert on start
-prepend : insert text at start of elvar (but cant use to get/replace text or html)
prepend was needed for start, after it made its easy to make append , not for a need , its just bcz lol

How to insert a HTML fragment and hold a reference to the outer element?

I've always wondered how this jQuery feature works: $('<span>Hello world</span>')[0]
That is supposed to return a reference to the newly created span element. How can I achieve the same result using the native DOM methods? insertAdjacentHTML? innerHTML? documentFragment?
I need to insert a HTML fragment and hold a reference to the outer element without the need of using createElement/appendChild.
Thanks.
It's possible to create an element, set its innerHTML, and return the first child. The container element is never added to the DOM:
var el = document.createElement('div');
el.innerHTML = '<span>Hello world</span>';
console.log(el.firstChild);
If that's wrapped in a function, I believe the original container will be eligible for garbage collection as soon as the child is appended somewhere else.
jQuery seems to be doing something more sophisticated, checking if the string contains a single tag or not, and creating a fragment for more complicated strings. See the parseHTML method on jQuery's source code.

Append a jQuery element to a string that contains html

I have a jQuery wrapped element which I would like to append to a html row. I can't wrap my head around this, since append() seemingly accepts strings but not existing jQuery elements (I might be mistaken here).
I have a following setup:
var row='<tr><td>data1</td><td>data2</td><td>';
var img=$('<img src="path/to/img.png"');
img.click(myClickHandler);
Now what I'm trying to do is to append this img element to my row and 'close' the row with a closing tag.
I'm doing it as follows:
var jRow=$(row);
jRow.append(img);
jRow.append('</td></tr>');
After my row is ready I append it to my table:
$('#tableId').append(jRow);
Well, all above doesn't work, because I get [Object Object] instead of image tag in my added row.
My goal is to have a row with an image in last cell and a working click handler.
Pleease, help.
When you pass a string to append() it is first "converted" to a DOM element/collection. So, every single string you pass to append() must be valid HTML/XHTML; you can't add bits of string on later. The image can still be appended to the table row even if you close the tags beforehand. E.g.
var row='<tr><td>data1</td><td>data2</td><td></td></tr>';
var img=$('<img src="path/to/img.png"/>');
img.click(myClickHandler);
var jRow = $(row);
$('td:last', jRow).append(img);
When you pass anything to append() or html() or prepend() (or any other similar method) try to forget about strings; what you just passed is no longer a string; it has been parsed as HTML and has been added to the document as a DOM element (or a number of DOM elements).
I am not 100% sure, but I think HTML fragments should always be "complete", meaning that adding just "</td></tr>" will not work.
A solution would be to build a string with a complete HTML fragment, and then append it, instead of appending the pieces one at a time. You can always add the click handler after you created your jQuery object, like this:
jRow.find("img").click(function () { ... });
How about trying with jRow.html(), like this?
$('#tableId').append(jRow.html());
It should return you the actual HTML contents instead of the jQuery-wrapped element (jQuery object), which is probably what causes the problem, since append() expects to get a String to append.
Attributes/html()
Manipulation/append()

Categories