Piping createElement and appendChild in JavaScript - javascript

Can someone please explain to me, why
var Node = document.createElement("testing");
var Parent = document.createElement("testingOne")
Parent.appendChild(document.createElement("hi"));
Node.appendChild(Parent);
produces a different result from
var Node = document.createElement("testing");
var Parent = document.createElement("testingOne")
.appendChild(document.createElement("hi"));
Node.appendChild(Parent);
In the second snippet the element testingOne doesn't even get included. Why does the piping do this?

Your first example will result in
<testing><testingone><hi></hi></testingone></testing>
Parent will contain the testingOne and the hi element will be appended to it.
While the second example will result in
<testing><hi></hi></testing>
Because Parent will contain the hi element, which is returned by the appendChild method.

Related

How to append more than 1 nested node for XML in javascript?

Good day everyone,
I am currently trying to append a metadata file. Sorry in advance if I did anything wrong, I am unfamiliar with editing XML codes in JS.. Thanks!
Currently, I am having difficulty getting the results that I expected. I am trying to insert 2 new nodes one nested over the other into the newParentTestNode.
I want to add a couple of nodes within the TestNode as seen in the results I want.. I can't seem to find a solution online. Please do help thanks!
I am currently getting this result:
<gmd:MTTEST><TESTNODE2/></gmd:MTTEST>
But the result I want is:
<gmd:MTTEST>
<gmd:TestNode>
<gmd:TestNode2>
</gmd:TestNode2>
</gmd:TestNode>
</gmd:MTTEST>
xmlTest: function (evt) {
if(this.item.metadata_standard_name == "Correct Data"){
xmlString = this.item.sys_xml_clob;
var metadataXmlString = jQuery.parseXML(xmlString);
let newParentTestNode = metadataXmlString.getElementsByTagName("gmd:MTTEST")
newNode = metadataXmlString.createElement("TestNode")
newNode2 = metadataXmlString.createElement("TestNode2")
let addMe = newNode.appendChild(newNode2)
newParentTestNode[0].appendChild(addMe)
xmlString = (new XMLSerializer()).serializeToString(metadataXmlString);
console.log(xmlString)
}
appendChild() returns the node that is appended not the parent node.
This means that newNode.appendChild(newNode2) returns newNode2, which you'll then append to your root node, effectively removing TestNode2 from TestNode and appending it directly to MTTEST.
You don't need to assign the result of appendChild to a new addMe variable because appendChild modifies the structure in-place, so you gain nothing from the return value (as you already have variables referencing both the parent and the child element). So in the end you just need to append newNode (which will already contain newNode2) to newParentTestNode.

How to get updated DOM element javascript

I am trying the fetch dynamic DOM elements from javascript and as per the current development, I can successfully fetch the updated DOM HTMLCollection array object. But when I try to print the innerHTML it gives previous DOM value. Below the console output which I am facing right now:
Console output for HTMLcollection: Highlighted part, that I want to fetch:
But when I try to get innerHTML for that element, I am getting the previous innerHTML instead I want to print current DOM innerHTML. Below is the screenshot of the output:
as we can see both screenshots of the same DOM element, gives different output. and this is javascript code I am trying fetch innerHTML:
var $wrap = document.getElementsByClassName('single_variation_wrap')[0];
var $deposit_amount = document.getElementById('deposit-amount');
var $display_amount = document.getElementsByClassName('woocommerce-variation single_variation');
$display_amount = $display_amount[0];
var $final_display_amount = document.getElementsByClassName('woocommerce-variation-price');
console.log($deposit_amount, $final_display_amount);
for(var i=0; i<$final_display_amount[0].childNodes.length;i++){
console.log($final_display_amount[0].childNodes[i].innerHTML);
}
Please suggest, where am I doing things wrong?

parentNode.removeChild not removing last element. But why?

I am working on a javascript code where I can clone an element, but also want to delete one on click. Cloning works, but I can't remove one.
I have the following elements.
<input list="accountsdeb" name="deblist[1]" id="deblist" autocomplete="off">
<input list="accountsdeb" name="deblist[2]" id="deblist" autocomplete="off">
And now I want to remove the last one on click (last = highest number).
function remove1() {
var dbl = document.querySelectorAll('#deblist').length;
var dbla = dbl;
var elem = document.getElementsByName("deblist["+dbla+"]");
alert(dbla);
//var last = debelelast - 1;
elem.parentNode.removeChild(elem);
}
As an orientation I used to have a look on an example from W3S and Stack. I have also seen that this works:
var elem = document.getElementById("myDiv");
elem.parentNode.removeChild(elem);
But this is random and as you can see I have tried to include this in my code.
The error I get is:
Uncaught TypeError: Cannot read property 'removeChild' of undefined
at HTMLAnchorElement.remove1 (index.php:179)
Where's the problem in my code, where is my thinking wrong?
I see two issues in the piece of code you provided,
deblist is used as id for 2 elements which is not advisable and due to this document.querySelectorAll('#deblist').length returns 2 (I am not sure if you intending to do so)
document.getElementsByName() (check here) will return a NodeList which needs to be iterated in order to access any of the returned elements. So here you need to select the child element by giving its index. In your case elem will have one element for the matched name deblist[2] and hence you need to access it like elem[0] for selecting its parent and deleting its child.
So the updated the code would be,
var dbl = document.querySelectorAll('#deblist').length;
var dbla = dbl;
// console.log('dbla', dbla);
var elem = document.getElementsByName("deblist["+dbla+"]");
// console.log('elem 0', elem[0]);
// console.log('elem parentNode', elem[0].parentNode);
//var last = debelelast - 1;
elem[0].parentNode.removeChild(elem[0]);
Check the fiddle here
If the inputs are part of a group they could share a name property or such, and the use of jQuery could help you do something like...
$("input[name='group1']").last().parent().remove()
Or if not part of a group then just....
$("input").last().parent().remove()

How can i change a reference to an element in javascript?

I would like to modify an element of my xml. I have to query it to find it, and then I only seem to be able to modify a copy of it. I use: clientXML.querySelector("[id=XMLIssue-9]").childNodes[2].textContent; to isolate the element in question.
I would like to just replace the element with this one newXMLIssue.childNodes[0]. They both have the exact same structure. I cant do:
clientXML.querySelector("[id=XMLIssue-9]") = newXMLIssue.childNodes[0];
because it causes an error to have the function on the left side of the equation. I also tried:
var x = clientXML.querySelector("[id=XMLIssue-9]");
x = newXMLIssue.childNodes[0];
but this only changes a copy of the element.
You have to call replaceChild on the parent:
var parent = clientXML.querySelector("[id=XMLIssue-9]");
parent.replaceChild(parent.childNodes[0], parent.childNodes[2]);

Is there any alternative to jQuery .after() function

I am trying to convert my jQuery script into javascript. I have a problem there..
I have a script that creates a node
var new_node = document.createElement("div");
new_node.className="tooltip";
new_node.innerHTML = html;
alert(new_node.className);
When i do this
jQuery(link).after(new_node);
It works fine. But I want to do it javascript way. I have tried using appendChild function but it gives some strange results.
Please help me out with this.
You're comparing jQuery's after with appendChild, but they do very different things. after puts the element after the reference element, appendChild puts it inside it.
You probably want insertBefore (with the reference node being link's nextSibling).
So:
var link = /* ... get the `a` element from somewhere ... */;
var new_node = document.createElement("div");
new_node.className="tooltip";
new_node.innerHTML = html;
link.parentNode.insertBefore(new_node, link.nextSibling);
If link is the last thing in its parent, that's fine; link.nextSibling will be null and insertBefore accepts null as the reference node (it means "insert at the end").
Assuming you already have a node instantiated as link, you could do what you want this way in plain Javascript:
link.parentNode.appendChild(new_node);
The link node would have to be the last node in its container. Otherwise you would have to find link's nextSibling and use insertBefore to put new_node in its proper place.
jQuery(link).append(new_node);

Categories