i want to dynamically add div element to my page.searching around including Stackoverflow gives me this sample code:
var main = document.getElementById('MasterContainer'); //manually defined div with this id
var div = document.createElement('div');
div.setAttribute("id","container1");
main.appendChild(div);
note: its inside a document.ready function.
and the result does not contain container1 div.
The code should be fine, check if the element with id #MasterContaienr is on the page and the name has been write well
Related
My code follows:
g = document.createElement('div');
g.setAttribute("id", "divcontainer");
g.innerHTML = `
HTML GOES HERE
`
When I use this on a site, I want the div centered and visible, it is working in the fact that it creates the div (tested that in console) but I cannot see it.
I am not using JQuery but if I need to, I can. My goal is to have a UI type thing.
Your code only creates the element but doesn't add it to the DOM, in order to do that you have to use document.body.appendChild(element) and that will add the element to the body element, you can also use the same method to add the element inside and element that you select by id or by QuerySelector.
You can modify your code as follows :
g = document.createElement('div');
g.setAttribute("id", "divcontainer");
g.innerHTML = `HTML GOES HERE`;
document.body.appendChild(g);
If you want to add multiple elements you can use append() instead of appendChild().
document.body.append(g,g2,g3,g4)
Hope that helps!
I have a button that, when pressed, executes something like
function click(){
element = document.getElementById("element");
element.parentNode.removeChild(element);
var newelement = document.createElement("div");
body.appendChild(newelement);
newelement.id = "element";
}
I have also tried using element.outerHTML = "" instead of removeChild with no success. Before adding the bit about deleting the previous element with the id "element" things worked fine on the first click and an div named "element" was appended to the body. (Of course, on the second click, another element named "element" is appended, and I want to keep the id unique to one element.) Now, with the bit about removing previous elements, my button.onClick doesn't even do anything.
Another important piece of context: I'm trying to do this for elements that are generated using user input, so there's no guarantee on how many of these things are made--I just want them deleted when the user wants to generate more of them.
On the first click, I'm attempting to remove an empty element. Does that break something?
body does not exist in the scope you've provided and would throw an exception. I would try:
var body = document.querySelector("body");
See this for a example using your code:
https://jsfiddle.net/k0wL4y7p/2/
Also make sure you use var on all local variables so they are not declared globally. See below to learn about variable scope:
When to use var in Javascript
How about this... don't remove the Parent Element (Div1); instead to remove the children. Then, create the child and append it to the parent element.
Note: you must iterate over it to remove all child nodes & for p element id p1/p2 generate dynamic id or use class if you need it.
Your JS:
$(document).ready(function() {
$("#btn1").click(function() {
var element = document.getElementById("div1");
while (element.firstChild) {
element.removeChild(element.firstChild);
}
var para = document.createElement("p");
var node = document.createTextNode("New element after click.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
});
});
I prefer JQuery - no loop
$(document).ready(function(){
$("#btn1").click(function(){
$("#div1").empty();
$("#div1").append(" <p>Appended element after click</p>");
});
});
Your Html
<body>
<div id="div1">
<p id="p1">Paragraph element before click.</p>
<p id="p2">Another paragraph beofre click.</p>
</div>
<button id="btn1">Remove </button>
</body>
Hope it helps.
I have this code which creates an element but the problem i am facing is it appends it at the very bottom of the page, in order for this to work i need it to be positioned in a certain place in the DOM how can i do this ?
var x = document.getElementById('options_10528_1');
var pos = document.getElementById('options-10528-list');
x.onclick = function(){
var elem = document.createElement('div');
elem.setAttribute("class","uk-warning");
elem.innerHTML = "Unfortunately, we cannot supply this medicine. Please consult your GP.";
document.body.appendChild(elem);
}
afterWhichNode.parentNode.insertBefore(newNode, afterWhichNode.nextSibling);
This code will insert a node after the afterwichNode, thats using vanilla javascript, if you are using jquery, just use .after()
Currently you are appending the element in the body tag, it will always goes at bottom. So if you want to append the element in a specific position, you have to append it in that container. let say you want to append it in "pos", you can do this:
pos.appendChild(elem);
I have a dynamically added div which I want to append in response to a click event.
The initial div is created and rendered when added however trying to add children divs to the first dynamic div does not render - yet in console log the dynamic div shows the new div has been added.
var newDiv = $('<div id="#newDiv'+pID+'" />').css({
display:"inline-block",
width:"90%",
height:"100px",
position:"relative"
})
var newHTML = "<div>some content</div>"
$(newDiv).html(newHTML)
$('#dynDiv'+ID).append($(newDiv))
console.log($('#dynDiv'+pID)) // displays code created successfully
So newDiv is not rendered nor present when "inspecting" the DOM using debugger.
Why is the second attempt to add dynamic content failing ??
Have you remembered to append it to something? Remember, jQuery can have DOM elements present in memory which are not part of the page:
newDiv.appendTo($(parentElement));
eg. http://jsfiddle.net/dTe73/
A couple of other possible errors:
# is not a valid character to put in an id in $('<div id="#newDiv'+pID+'" />')
$('#dynDiv'+ID) looks like a typo for $('#dynDiv'+pID) (or the other way around)
Not an actual error, but redundant use of $: $(newDiv) is absolutely equivalent to newDiv
I found the source of the problem was that the parent div to which I was adding the dynamic div was not unique - there were multiple elements with same name ! This makes sense that it would fail. Thanks for everyones input.
Replace $(newDiv).html(newHTML) with newDiv.html(newHTML)
and $('#dynDiv'+ID).append($(newDiv)) with $('#dynDiv'+ID).append(newDiv)
and it should work.
I basically have several divs each with ids "id_1", "id_2" "id_3" etc. The divs are all initially empty.
I want on page load to populate all the divs with certain html content. But the part that has been troubling me is that I also need to extract the unique id portion for use within the html:
<div id="id_3">
<div id="inner_3></div>
</div>
where the inner div is what gets printed. Notice that the '3' is extracted from the container div id by the javascript and then subsequently used and printed in the inner div.
Any ideas how to do this with jquery? Thanks in advance.
You can fetch all the div elements that have an id that starts with a certain string:
$(function() {
$('div[id^=id_]').each(function() {
var id = $(this).attr('id').split('_').pop();
$(this).html(
$('<div/>').attr('id','inner_' + id)
);
});
});
Then you loop through each, get the id, and do your HTML manipulation.
there are several ways of doing this, but in the end its just simple string manipulation. Here is an example:
// on page load
$(function(){
//find all divs and iterate through them - you can use any selector you like
$("div").each(function(){
//this gets the id attribute of the div we are currently on in the loop
var id = $(this).attr("id");
//this gets the number at the end - notice that its just string manipulation
var nid = id.slice(id.lastIndexOf("_") + 1)
//create inner div, give it an id and append
var innerDiv = $('div').attr("id", "inner_" + nid);
$(this).append(innerDiv);
//all done - you can append content to inner div here
// innerDiv.append(someContent);
});
});