How can I using javascript make clone of some <div> and set his id different from original. Jquery also will be nice.
var div = document.getElementById('div_id'),
clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "some_id";
document.body.appendChild(clone);
Use it:
JQuery
var clonedDiv = $('#yourDivId').clone();
clonedDiv.attr("id", "newId");
$('#yourDivId').after(cloneDiv);
I had the same problem. I've solved that by setting a counter and appending it to the ID. Hope it helps you too:
<script type="text/javascript">
var counter = 1; //Set counter
function clone(sender, eventArgs) {
var $row = $('#yourID');
var $clone = $row.clone(); //Making the clone
counter++; // +1 counter
//Change the id of the cloned elements, append the counter onto the ID
$clone.find('[id]').each(function () { this.id += counter });
}
</script>
jQuery have method clone()
var original = $("#original");
var newClone = original.clone();
Related
I have some id div with elements(classes and Ids), I need to clone it and append to my clone new class. How can I do it?
window.onload = Func ();
function Func () {
var temp = document.getElementById("start");
var cl = temp.cloneNode(true);
var div = document.createElement('div');
div.className = "class";
div.innerHTML = "MyText";
var result = cl.getElementById("second").append(div);
alert(result.innerHTML);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="start">
<div id="second">
Link
</div></div>
use following code
$(function(){
var $Div = $('.start').clone();
$('.second').html($Div);
});
Using JQuery,
var clone = $("#divName");
or var clone = $(".className")
var secondDiv = $("#secondDiv");
or var secondDiv = $(".secondDivClassName");
//Or you can get the html of your second div like this:
var myHtml = secondDiv.html(); //if you don't give any parameter, it takes the inner html of the given element.
//and finally insert your html into the clone like this :
clone.html(myHtml);// in this case, the html() methode takes a parameter and inserts the given parameters into the given element.
You should reference JQuery to your page.
Tell me if it works.
I am having an issue when cloning a section of my form (with jQuery).
The code below copies a 'fieldset', applies unique id's and for's, then appends the copy within the original 'fieldset'.
Although the copying works, all animations of the 'MDL'framework break on the copied 'fieldset'.
The code I am using is shown below:
//When add section is pressed
$('#add-section').click(function () {
// add 2 vars to count clicks per page
// get the fieldset's children that user is on, and clone it
var $fieldsetCopy = $('form>:nth-child(' + pageNumber + ')').clone();
// add '-2' to all id's of the cloned fieldset
$fieldsetCopy.find("*[id]").each(function () {
$(this).attr("id", $(this).attr("id") + "-2");
});
// add '-2' to all for's of the cloned fieldset
$fieldsetCopy.find("*[for]").each(function () {
$(this).attr("for", $(this).attr("for") + "-2");
});
// remove the first p element of the clone
$fieldsetCopy.find("p").first().remove();
// add the cloned fieldset within the original
$fieldsetCopy.appendTo('form>:nth-child(' + pageNumber + ')');
$()
});
I was guessing a problem be the JavaScript loading?
I ended up finding the answer myself. The problem was that the framework needed to be reloaded. To do this you can use the line:
componentHandler.upgradeAllRegistered();
Or, if you would like to target a specific element you can use:
componentHandler.upgradeElement(button);
The full documentation is here https://getmdl.io/started/#dynamic
Here is another example (without jQuery). Maybe it will help. Just rebuild the DOM manually.
<script type="text/javascript">
document.getElementById("addText").onclick = function () {
var form = document.getElementById("container_layout_text");
var newDiv = document.createElement("div");
newDiv.className = "mdl-textfield mdl-js-textfield mdl-textfield--floating-label desc_value";
var newInput = document.createElement("input");
newInput.className = "mdl-textfield__input";
newInput.type = "text";
var newLabel = document.createElement("label");
newLabel.className = "mdl-textfield__label";
newLabel.textContent = "kkk?";
newDiv.appendChild(newInput);
newDiv.appendChild(newLabel);
componentHandler.upgradeElement(newDiv);
form.appendChild(newDiv);
}
I have a div and a button to close that div. I am cloning them both separately and assigning a unique incrementing id to both. Everything is working in that the cloning happens and the button closes the Div.
I have a problem though regarding the placement of the button. I want the button to always be in the same position with reference to its cloned div. Any ideas how to do this?
HTML
X
<div id="id"></div>
Add
Javascript
function duplicateDiv(){
$('#btn').clone().attr('id', 'btn'+ cloneCount2++).insertBefore($('[id^=id]:first'));
$('#id').clone().attr('id', 'id'+ cloneCount++).insertAfter($('[id^=id]:first'));
//clearing the input items in the new cloned div
$("#id").find("input").val("");
}
function hideDiv(obj){
var currentId = $(obj).attr('id');
var divId = currentId.replace("btn", "id");
$("#"+divId).hide();
$("#"+currentId).hide();
}
If interpret Question correctly , try using .appendTo() , .insertAfter($("#btn" + cloneCount))
var cloneCount = 0, cloneCount2 = 0;
function duplicateDiv() {
//the close button
$("#btn")
.clone().attr("id", function(_, id) {
return id + (++cloneCount2)
})
.appendTo("body")
$("#id")
.clone().attr("id", function(_, id) {
return id + (++cloneCount)
})
.insertAfter($("#btn" + cloneCount))
//clearing the input items in the new cloned div
$("#id").find("input").val("");
}
function hideDiv(obj) {
var currentId = $(obj).attr('id');
var divId = currentId.replace("btn", "id");
$("#" + divId).hide();
$("#" + currentId).hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
X
<div id="id">div</div>
Add
One of the way is Jquery Offset
var destination = $('.original-content').offset(); // get position of original
$('.original-content').hide(); // hide original
$('.cloned-content').css({top: destination.top, left: destination.left}); // set position of cloned
I have a jQuery script which creates div in this fashion
function dump_template(src,close_div)
{
var item_template = $('<img/>', {'id':'target','src':src});
var first_text = $('<div/>', {'id':'first_text','class':'edit_text'});
$(first_text).css({"left":"0px",
"top":"0px",
"color":"#fff",
"position":"relative",
"width":"auto",
"text-align":"center"});
$(first_text).html('Demo First Text');
var second_text = $('<div/>', {'id':'second_text','class':'edit_text'});
$(second_text).css({"left":"0px",
"top":"0px",
"color":"#fff",
"position":"relative",
"width":"auto",
"text-align":"center"});
$(second_text).html('Demo Second Text');
$('#main_canvas').html(item_template);
var width = $("#target").width();
var height = $("#target").height();;
$('#main_canvas').css({'height':height+'px','width':width+'px'});
var drag_first_text = $('<div/>', {'id':'drag_first_text','class':'context-menu-text'});
var drag_second_text = $('<div/>', {'id':'drag_second_text','class':'context-menu-text'});
$(drag_first_text).css({"left":"20px",
"top":"100px",
"position":"absolute",
"width":"auto",
"z-index":"5",
"text-align":"center",
});
$(drag_second_text).css({"left":"20px",
"top":"150px",
"position":"absolute",
"width":"auto",
"z-index":"5",
"text-align":"center"});
$(drag_first_text).append(first_text);
$(drag_second_text).append(second_text);
$('#main_canvas').append(drag_first_text).append(drag_second_text);
$(drag_first_text).draggable({grid:[1,1]});
$(drag_second_text).draggable({grid:[1,1]});
HideModalPopup(close_div);
}
Now I have some code in jQuery like this:
var content = $(this).find('.edit_text').text();
var outside_div_id = $(this).id;
alert(outside_div_id);
var inside_div_id = $(this).find('.edit_text').id;
alert(inside_div_id);
Here in the above example of code, $(this) refers to the div with ids "drag_first_text" and "drag_second_text" corresponding to the selected div.
But alert(outside_div_id); and alert(inside_div_id); both gives me undefined.
How can I find the glitch?
You either need to convert that to native Element using get or using index or use attr("id")
var outside_div_id = $(this)[0].id; // or $(this).attr("id")
alert(outside_div_id);
There is no such thing as .id.
var outside_div_id = $(this).attr('id');
alert(outside_div_id);
var inside_div_id = $(this).find('.edit_text').attr('id');
alert(inside_div_id);
Let me know if you have any question.
this looks simple enough but I just can't get it to work. I could add DOM elements but I just can't remove them when using an array.
<script language="javascript">
fields = 0;
count = 0;
function addInput() {
if (fields != 10) {
var htmlText = "<input type='search' value='' name='field[]' />";
var remButton = "<input type='button' value='del' onclick='remove()' />";
var newElement = document.createElement('div');
newElement.id = 'SomeID'+fields;
newElement.innerHTML = htmlText + remButton + newElement.id;
var fieldsArea = document.getElementById('text');
fieldsArea.appendChild(newElement);
fields += 1;
} else {
...
}
count++;
}
// NEED HELP FROM HERE PLEASE
// You don't need to Loop, just get the button's id and remove that entire 'SomeID'
function remove() {
fieldsArea = document.getElementById('text');
fieldsArea.removeChild(SomeID1); <-----------------------THIS WORKS!
fieldsArea.removeChild(SomeID+count); <------------------THIS JUST WOULDN'T
count--;
}
</script>
In the remove function, writing SomeID1 works and delete the first added element but when I try to use a 'count', I just can't delete my 'elements'.
Any help would be most appreciated.
Thank you!
You have to get a reference to the element first. Currently you are passing an undefined variable SomeID to the function.
E.g.:
var element = document.getElementById('SomeID' + fields);
// or starting by zero: var element = document.getElementById('SomeID0');
element.parentNode.removeChild(element);
If you want to remove the div for which the button was clicked, you have to pass a reference to the corresponding div to the remove function.
'<input type="button" value="del" onclick="remove(this.parentNode)" />';
this will refer to the button and as it is a child of the div, this.parentNode refers to that div.
You also have to change your function to accept the element that should be removed:
function remove(element) {
element.parentNode.removeChild(element);
count--;
}
You probably also have to update fields, but I'm not sure how your code is supposed to work.
If you want to remove all of them you have to loop:
for(;fields--;) {
var element = document.getElementById('SomeID' + fields);
element.parentNode.removeChild(element);
}
Also have a look at the documentation of removeChild.
The removeChild needs a node (DOM element) as parameter. In this case
fieldsArea.removeChild(SomeID+count);
you could for example pass the node this way
fieldsArea.removeChild(document.getElementById('SomeID'+count));