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.
Related
How do I make a button using javascript that makes a new div element with a new id each time the button is pressed.
This is what I want the html to look like. But I want it to be made with javascript.
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
I am a new self taught coder so be gentle please.
Thanks.
You can create a element using document.createElement() method, then set it's id by id property and then append it to the DOM, in this case I appended the element to the body.
var element = document.createElement("DIV");
element.id = "4";
document.body.appendChild(element)
Here is an example of generating an element on button click with new id each time:
var base = 0;
function addElement() {
base++
var element = document.createElement("DIV");
element.id = base;
element.innerHTML = base
document.body.appendChild(element)
}
<button onclick="addElement()">Add element!</button>
var base = 0;
function addElement() {
base++
var element = document.createElement("DIV");
element.id = base;
element.innerHTML = base
document.body.appendChild(element)
}
You can do it using a static id variable to keep track of the generated incremented number.
For the div generation, you can use the document.createElement method which creates the HTML element specified by tagName (div in your case)
let id = 0;
function createDiv(){
var element = document.createElement("DIV");
element.id = id;
element.textContent = id;
id++;
document.body.appendChild(element)
}
<button onclick="createDiv()">Add div</button>
what I want something like this
var newDiv = document.createElement("div");
newDiv.innerHTML = data;
var List=newDiv.$(".myclass h4");
console.log($(List[0]).html());
but it doesnot work.
If you make that newDiv a jQuery object, and then use find(), you can get the other element within it.
$(newDiv).find(".myclass h4");
Stack snippet
var data = "<div class='myclass'><h4>hello</h4></div>"
var newDiv = document.createElement("div");
newDiv.innerHTML = data;
var List = $(newDiv).find(".myclass h4");
console.log( $(List).html() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
An alternative is passing as the second parameter the created element as the parent/source DOM element to find elements from it.
$(".myclass h4", newDiv); <--- This call returns a jQuery object.
^
|
+--- Parent/Source element
var newDiv = document.createElement("div");
newDiv.innerHTML = '<div class="myclass"><h4>Ele from Stack</h4></div>';
var list = $(".myclass h4", newDiv);
console.log(list.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm going to load several new elements (via AJAX) into the DOM. After that I want to "refresh" the document variable to select existing and new elements.
I tried to simplify my question with this small example:
// Creating a new element and insert it into DOM
var newdiv = document.createElement('div');
newdiv.style.color = 'red';
newdiv.innerHTML = 'this is a new div container';
newdiv.classList = 'newdiv';
document.getElementById('existingdiv').appendChild(newdiv);
// Search the complete DOM for the new element and try to select it (but abc is null)
var abc = document.querySelector('newdiv');
abc.style.color = 'blue';
Any ideas (without jQuery)?
newdiv is a class not an element. To target that you have to specify dot (.) along with class name in the selector:
var abc = document.querySelector('.newdiv');
After that I want to "refresh" the document variable to select existing and new elements.
There's no need, document is live.
querySelector('newdiv') looks for an element with the tag name newdiv. You probably meant querySelector('.newdiv'), which looks for the first element with that class in the DOM.
Live Example:
// Creating a new element and insert it into DOM
var newdiv = document.createElement('div');
newdiv.style.color = 'red';
newdiv.innerHTML = 'this is a new div container';
newdiv.classList = 'newdiv';
document.getElementById('existingdiv').appendChild(newdiv);
// Search the complete DOM for the new element and try to select it (but abc is null)
var abc = document.querySelector('.newdiv');
abc.style.color = 'blue';
<div id="existingdiv"></div>
I am creating a light box in pure JavaScript. For that I am making an overlay. I want to add this overlay to body but I also want to keep the content on the page. My current code adds the overlay div but it also removes the current contents in body. How to add div element and keep contents on body?
var el = document.getElementById('element');
var body = document.getElementsByTagName('body');
el.innerHTML = '<p><a id="clickme" href="#">Click me</a></p>';
document.getElementById('clickme').onclick = function (e) {
e.preventDefault();
document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
}
Using Javascript
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.appendChild(elemDiv);
Using jQuery
$('body').append('<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>');
Try this out:-
http://jsfiddle.net/adiioo7/vmfbA/
Use
document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
instead of
document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
Edit:-
Ideally you should use body.appendChild method instead of changing the innerHTML
var elem = document.createElement('div');
elem.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000';
document.body.appendChild(elem);
Instead of replacing everything with innerHTML try:
document.body.appendChild(myExtraNode);
improving the post of #Peter T, by gathering all solutions together at one place.
Element.insertAdjacentHTML()
function myFunction() {
window.document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID" style="color:blue;"> With some data...</div>' );
}
function addElement(){
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'width:100%;height:10%;background:rgb(192,192,192);';
elemDiv.innerHTML = 'Added element with some data';
window.document.body.insertBefore(elemDiv, window.document.body.firstChild);
// document.body.appendChild(elemDiv); // appends last of that element
}
function addCSS() {
window.document.getElementsByTagName("style")[0].innerHTML += ".mycss {text-align:center}";
}
Using XPath find the position of the Element in the DOM Tree and insert the specified text at a specified position to an XPath_Element. try this code over browser console.
function insertHTML_ByXPath( xpath, position, newElement) {
var element = document.evaluate(xpath, window.document, null, 9, null ).singleNodeValue;
element.insertAdjacentHTML(position, newElement);
element.style='border:3px solid orange';
}
var xpath_DOMElement = '//*[#id="answer-33669996"]';
var childHTML = '<div id="Yash">Hi My name is <B>\"YASHWANTH\"</B></div>';
var position = 'beforeend';
insertHTML_ByXPath(xpath_DOMElement, position, childHTML);
The most underrated method is insertAdjacentElement.
You can literally add your HTML using one single line.
document.body.insertAdjacentElement('beforeend', html)
Read about it here - https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement
The modern way is to use ParentNode.append(), like so:
let element = document.createElement('div');
element.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.append(element);
You can make your div HTML code and set it directly into body(Or any element) with following code:
var divStr = '<div class="text-warning">Some html</div>';
document.getElementsByTagName('body')[0].innerHTML += divStr;
Try doing
document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>'
The best and better way is to create an element and append it to the body tag.
Second way is to first get the innerHTML property of body and add code with it. For example:
var b = document.getElementsByTagName('body');
b.innerHTML = b.innerHTML + "Your code";
Here's a really quick trick:
Let's say you wanna add p tag inside div tag.
<div>
<p><script>document.write(<variablename>)</script></p>
</div>
And that's it.
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();