Append a jQuery element to a string that contains html - javascript

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()

Related

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

Why is insertAdjacentHTML converting HTML into an object

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]);

Insert HTML into all Elements

I am having an issue were jQuery is not inserting the specified html element into all instances of #element. However, it is only inserting it into the first element but not the other 3 with that id.
var htmlcode = '<div class="block"></div>';
$('#element').html(htmlcode);
If I switch it to $('div') it will work but this isn't what I want. I need to have this inserted into all divs with the id of #element. From what I understand from the documentation this should be working?
Ids must be unique on a page. As they are implemented as a fast-lookup dictionary there is only one element stored against each key/id.
jQuery and JavaScript can only see the first one because of this.
Use a class instead.
e.g.
$('.element').html(htmlcode);

JQuery working wierdly for function 'find':

I have the following jQuery line:
$('<html>hi</html>').find('a')
I expect the result to be a wrapped set of one element. However the result is an empty array ([]). Why?
-- EDIT --
For some reason the code below works.
$('<html><div>hi</div></html>').find('a');
Why is this happening?
That's because the html element is stripped when the string is parsed:
> $('<html>hi</html>')
[​hi​​]
i.e. the current collection contains an element that you are trying to find(). As the top-level a element doesn't (and can't) have a descendants the find() call will return an empty collection.
From jQuery documentation:
When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.
edit: The second snippet can find() a element as when the html element is stripped the top-level element of the collection is a div element that does have a descendant.
As in the Documentation of .find() descriped
Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
$('<html>hi</html>')
will just provide an Object of your a-tag.
Demo
If there are multiple anchor-tags inside your html-string you can filter them, e.g.:
var elem = $('<html>hihi</html>');
var filter = elem.filter(function(){
return $(this).attr('href') === "cnn.com";
});
Demo
Edit
When passing in complex HTML, some browsers may not generate a DOM
that exactly replicates the HTML source provided. As mentioned, jQuery
uses the browser's .innerHTML property to parse the passed HTML and
insert it into the current document. During this process, some
browsers filter out certain elements such as <html>, <title>, or
<head> elements. As a result, the elements inserted may not be
representative of the original string passed.
Source: http://api.jquery.com/jQuery/#jQuery2 down to the Paragraph Creating New Elements
So jQuery uses .innerHTML. According to the docs
Removes all of element's children, parses the content string and
assigns the resulting nodes as children of the element.
So the html-string <html>test</html> gets stripped to <a></a>.
When wrapping a div around the anchor, the anchor stays a descendat of an elemnt and therefore gets found by the .find()-function.
You should read the documentation at Jquery docs about find()
$('html').find('a');
Check this jsfiddle

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

Categories