Setting a new id for each button press using javascript - javascript

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>

Related

JavaScript: DOM manipulation and after that a search over all elements

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>

How can I clone element and append to the clone another el?

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.

create div for each createelement, javascript

How to create div in javascript for each create elements(DOM) and retrieve their values?
for (i = 1; i <= 3; i++) {
var input = document.createElement('input');
input.setAttribute("id", "x" + i);
var div = document.createElement('div');
div.id = "div"+i;}
I'm assuming you want to append all of your inputs into your divs and then your divs into the body.
Use the function appendChild, which is available on all DOM nodes, furthermore, your code will not work since inputVN is undefined.
you can try with this
document.body.appendChild(element);
example for create a div with javascript
var Div = document.createElement('div');
Div.id = 'DivId';
document.body.appendChild(Div);
this is a little example how create a div, you can try with these

How to create dynamic div in javascript without using jquery?

I want to make dynamic division on button click on my web page please tell me easiest solution, I am new to JavaScript.
Hope this will help
function divcreate() {
var div = document.createElement("div");
div.setAttribute("id", "mydiv");
div.className = "mdiv";
div.style.display = "none";
document.body.appendChild(div);
}
To create an element, use the createElement method
var mydiv = document.createElement('div');
//mydiv is a variable containing a newly created div
<button onclick="createDiv()">Click Me</button>
function createDiv(){
var newDiv = document.createElement('div');
}
//create a div like below
var div=document.createElement("div");
var node=document.createTextNode("This is new.");
div.appendChild(node);
Then append the above div to which you want it to be child
var element=document.getElementById("some_parent_tag");
element.appendChild(div);

Adding div element to body or document in JavaScript

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.

Categories

Resources