insertBefore attaching element only at the last element of a loop - javascript

I have a set of rows where I want to add another set of rows. I'm trying to do it as loop all the rows and then on each row I did insertAfter operation.
let rows_to_be_attached = parent_tr.nextAll().not('.newly-rows');
let rows_to_attach = parent_tr.nextAll('tr.newly-rows').not('.mia');
$(rows_to_be_attached).each(function(i, el) {
$(rows_to_attach).insertAfter($(el));
}
It only attached the rows_to_attach 'tr's' at the last el. Why?

You are inserting the same element on each loop so it will move from the previously inserted place in DOM instead of that clone and insert it.
$(rows_to_be_attached).each(function(i , el){
added_rows.clone().insertAfter($(el));
})
If there is multiple and you want to insert one by one then use the index to get the element.
$(rows_to_be_attached).each(function(i , el){
added_rows.eq(i).insertAfter($(el));
})

Related

JQuery append method multiple parent elements append same element

As the API document declared:
If an element selected this way is inserted into a single location
elsewhere in the DOM, it will be moved into the target (not cloned).
Important: If there is more than one target element, however, cloned
copies of the inserted element will be created for each target except
for the last one.
var div = $("<div></div>").addClass("divCells"),
tdName = $("<td></td>").addClass("tdName"),
tdAge = $("<td></td>").addClass("tdAge"),
tdGender = $("<td></td>").addClass("tdGender"),
tds = [tdName, tdAge, tdGender],
tr = $("<tr></tr>"),
tbody = $("#peopleList tbody");
tds.append(div);
tr.append(tdName).append(tdAge).append(tdTimetdGenderstamp);
tbody.append(tr);
As above code represents, I try to include the 3 tds in to an Array, so that I could append div into all of them, but it is not working.
You're trying to use jQuery .append on a vanilla JavaScript Array. .append only works on jQuery/DOM elements, not JavaScript types such as Arrays.
Your tds array contains jQuery/DOM elements, but the Array itself isn't 'appendable' in the manner you're attempting.
Using an Array, you'll have to iterate through your array, and manually append the div to each element in it. Furthermore, since you will be appending to 3 separate elements individually (i.e. 1 per iteration, not all 3 at the same time) you'll have to manually .clone the div yourself, otherwise you'll just be appending the one div to the 1st item in the Array, and then moving the same div to the 2nd, and again to the 3rd. So...
// tds.append(div); // Change this to...
for (var i=0; i< tds.length; i++) {
tds[i].append(div.clone())
}
OR...
You could forget about using the Array altogether, and have jQuery clone and append the div for you (as your original question implied). Here's how...
// Remove the following lines...
// tds = [tdName, tdAge, tdGender],
// tds.append(div);
// Then, after you add the td's to your row here...
tr.append(tdName).append(tdAge).append(tdGender);
// ...have jQuery find all the td's and clone+append your div to them in one hit:
tr.find('td').append(div)

Get last added element of an element

I have a pivot element and I want that whenever an element is added to this pivot element a javascript function is called on it. The call must happen exact once per element.
DOMNodeInserted is marked as deprecated so I tried to use the workaround found here. The approach is working fine, but in addition to the element to which the addition happended (event.target), I also need to know which element was added.
Do I have to keep record of all elements added to my pivot element and then compare them after the event happened to detect new elements or is there an easier approach?
If your variable references a node, to retrieve the last item added to it you can use the lastChild property.
var node = document.getElementById("something");
var last = node.lastChild;
last.appendChild(document.createTextNode("I'm the last one..."));
An alternative may be childNodes:
var node = document.getElementById("something");
node.childNodes[node.childNodes.length - 1].appendChild(document.createTextNode("I'm the last one..."));
For extra reference: https://developer.mozilla.org/en-US/docs/Web/API/Node/lastChild
and https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes

Jquery clone method to clone mutliple (more than one) div's (not a single div multiple times) inside a page

I need a method to clone say 4 div's with id's like d_1, d_2, d_3, d_4
including the contents inside each div all at once and then detach all divs, and then I need to find copy of d_1 and its contents from the clone and append it again to the page.
something like:
var cloned=$('[id^="d_"]').clone();
$('[id^="d_"]').detach();
and then find div with id =d_1 from clone and append it to body.
Is it possible?
Use Document Fragment.
var $documentFragment = $(document.createDocumentFragment());
$('[id^="d_"]').each(function(){
$documentFragment.append($(this).clone().addClass("_cloned"));
});
$documentFragment.clone().appendTo(document.body);
If you want looking for an element into the fragment, you can do this:
$(document.body).find("#d_1._cloned"). ... ;
If you want to remove all the element and then append only the first copied into fragment:
$("._cloned", document.body).remove();
$documentFragment.find("#d_1").clone().appendTo(document.body);
You can appendTo() an element to detach and move an element elsewhere.
var els = $('[id^="d_"]')
els.detach();
els.each(function() {
if (this.id.indexOf('d_1') !== -1) {
$(this).appendTo(document.body);
}
});
// do something else with els later, too.

Append child in DOM table

I am using clone to add new row to the DOM table dynamically from a button click event like below mentioned. but i want to append the cloned node to a specific row position in the DOM table. i know i can do that by using "insertrow" option but i want to use this using clone.
var newNode = tblBody.rows[1].cloneNode(true);
tblBody.appendChild(newNode);
is there any way to insert or append the "newNode" in a position i dynamically choose rather appending it as last row.
Use .insertBefore() from tblBody, and pass the newNode as teh first argument, and the child of tblBody before which the node should be inserted as the second argument.
// put this node----v before this----v
tblBody.insertBefore(newNode, tblBody.rows[i]);
If tblBody.rows[i] is null or undefined, then .insertBefore() will just behave like .appendChild(), and put it at the end.
node.insertBefore() is what you are looking for: https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore

Changing the ID of html elements

I have a form which allows user to add elements(which might be a field set or a text box) dynamically. I'm able to assign a new ID to the elements when added but I'm not able to make it in a sequence as the user can add elements in between as well.
So for example, there is an Id named XXX1 and the user adds a new element after it which is xxx2. Now if the user adds a new element again after XXX1, it comes up as XXX3. So the order of the elements is XXX1, XXX3, XXX2. I'm not able to control the names when it is being added. So I'm trying to re-assign the names after add.
I'm trying to get all elements in an array and change the ID as follows
document.getElementById('xxx3').setAttribute('id', 'xxx2');
But this doesn't work as ID XXX2 already exists for another element. Please help me with a solution for this.
So why not change the ID of xxx2 first, to move it out of the way, then putting it back in place later?
document.getElementById('xxx2').setAttribute('id', 'temporaryId');
document.getElementById('xxx3').setAttribute('id', 'xxx2');
document.getElementById('temporaryId').setAttribute('id', 'xxx3');
Why not go from the last element to the first(the one's after the position you are inserting to) and add one to the ID?
for example:
var insertAt = 2; // for an element to be called xxx2
var els = [...]; // an array with all of the elements
if(els.length >= insertAt){
for(var i = els.length-1; i >= insertAt-1; --i){
els[i].setAttribute('id', 'xxx'+(i+2));
}
}
// Add the new element here which will be called xxx2

Categories

Resources