Add DOM elements to beginning of parent - javascript

I have the following javascript working to insert AJAX responses into a div with id results:
document.getElementById("results").innerHTML=xmlhttp.responseText;
However, this adds all new elements after those already present. I need for the new elements to be inserted before everything else.
I know this is probably very trivial but I can't seem to find anyway to do it myself.
Thanks for any help!

With modern js you can utilize the prepend method. Currently caniuse.com says only of IE, Edge, and OperaMini are not supported.
ParentNode.prepend(nodesToPrepend);
e.g.,
ParentNode.prepend(newDiv);
Also, it automatically converts text into a text node so you could do the following for your use case:
document.getElementById("results").prepend(xmlhttp.responseText);

You want either this
results.insertAdjacentHTML( 'beforebegin', xmlhttp.responseText );
or this
results.insertAdjacentHTML( 'afterbegin', xmlhttp.responseText );
(the variable results of course being a reference to the DOM element)
So, the first one will insert the new content before the element itself (as a previous sibling), and the second one will insert it inside the element before any other children).

I don't remember the exact syntax, but it something like:
var newDiv = document.createElement("div");
newDiv.innerHTML=xmlhttp.responseText;
document.getElementById("results").childNodes.addAt(0,newDiv);
if you can use jQuery, it's just simple as:
$("#results").prepend(xmlhttp.responseText);

Related

Express item.parentElement.remove() in a way that is supported by IE

From what I understand, the
remove()
function is not supported in IE. I have a JS function that creates a div and appends it to an existing list.The div contains another div styled as a button (this is the 'item' in the title, that's what I called it when I got it from HTML), which, on click, removes its parentNode (and consequently itself) from the DOM (by means of remove()), though it still 'exists' in that JavaScript can read it's data and stuff. I need a way to remove it from the DOM, as well as all of it's child elements. Setting it's innerHTML equal to nothing will not work, nor will setting it's display to none. Any idea how to do this in a way compatible with IE?
Any help appreciated, please no jQuery or other frameworks.
Anytime you would use .remove(), you can always just use .removeChild() instead with slightly different code around it.
So, if you wanted to do to remove the parent of a given node:
item.parentElement.remove();
Then, you can instead do this:
var p = item.parentNode;
p.parentNode.removeChild(p);
If you want to put this in a utility function, you can do this:
function removeNode(node) {
node.parentNode.removechild(node);
}
And, in your case, instead of item.parentElement.remove() you would call it like this:
removeNode(item.parentNode);
Note, I'm using parentNode instead of parentElement since you appear to want IE compatibility with older versions of IE. parentNode and parentElement are not exactly the same, but it's very rare where parentNode would be different than parentElement (in fact, I can't think of a case in a normal DOM where it wouldn't be appropriate to use parentNode). See Difference between DOM parentNode and parentElement for a discussion of the differences.

jQuery: render element to the DOM, then select it with jquery selector

Trying to understand something here: if I render something to the DOM from javascript, and want to call jQuery methods on it, it behaves differently than if I "re-select" the element from the DOM. Here's a simple example, in CoffeeScript:
element = """
<div id="my_div">TEST!</div>
"""
$('body').html(element)
element.hide() #this doesn't work.
$(element).hide() #this doesn't work either.
$('div#my_div').hide() #this does.
So, I seem to be misunderstanding something here. I guess the element variable is just a string and jQuery doesn't understand that it has been added as an element in the DOM.
Is there a different way to insert content into the dom, then, so that it behaves like a normally-selected jQuery object once it has been inserted?
The reason the first line doesn't work is because element is a string. The reason the second line doesn't work is because it ends up creating another DOM version of the string.
The fix would be to maintain a ref to the DOM version of the element the first time you construct it (in JS):
var $elem = $(element);
$elem.appendTo(document.body);
$elem.hide() // should work
Hope that helps.
I think you need:
element = $('<div id="my_div">TEST!</div>');

Replace part of innerHTML without reloading embedded videos

I have a div with id #test that contains lots of html, including some youtube-embeds etc.
Somewhere in this div there is this text: "[test]"
I need to replace that text with "(works!)".
The normal way of doing this would of course be:
document.getElementById("test").innerHTML = document.getElementById("test").replace("[test]","(works!)");
But the problem is that if i do that the youtube-embeds will reload, which is not acceptable.
Is there a way to do this?
You will have to target the specific elements rather than the parent block. Since the DOM is changing the videos are repainted to the DOM.
Maybe TextNode (textContent) will help you, MSDN documentation IE9, other browsers also should support it
Change your page so that
[test]
becomes
<span id="replace-me">[test]</span>
now use the following js to find and change it
document.getElementById('replace-me').text = '(works!)';
If you need to change more than one place, then use a class instead of an id and use document.getElementsByClassName and iterate over the returned elements and change them one by one.
Alternatively, you can use jQuery and do it even simpler like this:
$('#replace-me').text('(works!)');
Now for this single replacement using jQuery is probably overkill, but if you need to change multiple places (by class name), jQuery would definitely come in handy :)

How to insert created object into a div

I created an iframe using jQuery that I want to insert into an existing div element. However, when I use innerHTML to insert it, it shows up as: "[object HTMLIFrameElement]"
What could be the reason for this?
Here is the example: http://jsfiddle.net/MarkKramer/PYX5s/2/
You want to use the appendChild method rather than innerHTML. Change the last line in the JSFiddle from
iframediv.innerHTML = iframe;
to
iframediv.appendChild(iframe);
Edit to actually answer your question:
Your variable iframe is a reference to a DOM element. It's object representation is an <iframe> element while its textual representation is simply [object HTMLIFrameElement].
By using innerHTML you are attempting to insert its textual representation into the DOM. This is just how the method works. You may come across JS code where elements are added to the DOM via innerHTML, but it's always with text, e.g.
element.innerHTML = '<div>some text</div>';
In this case the browser will correctly add a <div> node as a child of element.
For your <iframe> element to be inserted into the DOM using the variable iframe, you must use the appendChild method which will add the IFrame object as a child node to iframediv.
$('#iframecontainer').append(iframe);
instead of
var iframediv = document.getElementById('iframecontainer');
iframediv.innerHTML = iframe;
should fix the problem
var new_iframe = $("<iframe></iframe>");
new_iframe.appendTo($("#div_to_insert_into"));
The idea behind (most) of the posted solutions is that you can work with your iframe and it's container as jQuery objects instead of regular dom elements. A jQuery object is a reference to a div or an iframe that has access to all of jQuery's awesome methods... like .append() and .click().
Generally speaking, jQuery's real purpose is to turn lines of code like
var iframediv = document.getElementById('iframecontainer');
...into ...
var iframediv = $("#iframecontainer");
...which you can then use to do with whatever you please, like
iframediv.appendTo("#anotherDiv");
Good luck.

How to read all child elements with tag names and their value from a xml file?

I've a xml file in which I'm storing some HTML content in an element tag called <body>. Now I'm trying to read all the HTML content of body tag using XML DOM in JavaScript.
I tried this code:
var xmlDoc=loadXMLDoc('QID_627.xml');
var bodytag = xmlDoc.getElementsByTagName("body");
document.write(bodytag);
but it is showing [object HTMLCollection] message on the browser screen.
Try this:
var xmlDoc=loadXMLDoc('QID_627.xml');
var bodytags = xmlDoc.getElementsByTagName("body");
document.write(bodytags[0]);
getElementsByTagName returns an array of elements (even if just one is found) so you need to subscript the array to retrieve your element.
Andrew Hare pointed out that getElementsByTagName() always returns an array, so you have to use bodytag[0] to get the element you want. This is correct, but not complete since even when you do that you'll still get an equally useless "[object ElementName]" message.
If you're set on using document.write() you can try to serialize out the content of the body tag with
document.write(bodytag[0].innerHTML);
Better yet would be directly attaching the source DOM nodes into your destination DOM.
You'd use something like
document.getElementById("destinationNodeId").appendChild(bodytag[0]);
There may be some issues with attaching DOM nodes from another document that may require you to copy the nodes, or jump through some other hoops to have it work.
You need to use document.write(bodytag.toXMLString());
EDIT: Andrew Hare also points out you need to subscript first. I think you may still need to use the toXMLString call as well.

Categories

Resources