Position an element in certain place in DOM JavaScript - javascript

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);

Related

I have created an element in plain css by a bookmarklet. It is created, but not visible

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!

Display outerHTML of multiple elements when the element is created by user

I have a JavaScript program that will create an element each time a button is pressed.
I use:
var element = document.createElement("div");
element.innerHTML = "hi";
document.body.appendChild(element);
I want to make it so when a user creates an element by clicking the button, then it will generate the element's html code or the outerHTML. But I also want it to do this if the user clicked the first button multiple times. So that means that I want it to generate the outer html for every element they make when they push the button. For this, I use:
function CreateElement() {
var element = document.createElement("div");
element.innerHTML = "hi";
document.body.appendChild(element);
var code = element.outerHTML;
}
However, the problem is that there are multiple elements that were created that were under the variable "element". So I want the, "code" variable to contain the outerHTML of all of the elements. I've tried:
function createElement() {
var code = element.outerHTML;
code = code + element.outerHTML //will add the outer html to the variable each time a new element is created
}
...but it always just replaces the whole variable instead of adding the outerhtml to the variable each time the button is clicked to make an element. My goal is to make the variable "code" look something like "<div>hi</div> <div>hi</div>" (as a string)
Thanks for any help
Append each dynamic element into a single container, then take that container's innerHTML:
const container = document.querySelector('.container');
const button = document.querySelector('button');
function createElement() {
var element = document.createElement("div");
element.textContent= "hi";
container.appendChild(element);
console.log(container.innerHTML);
}
button.onclick = createElement;
<button>click</button>
<div class="container"></div>
Also, just a suggestion regarding element.innerHTML = "hi"; - best to only use innerHTML when deliberately setting or retrieving HTML markup. If you just have text, it's faster, safer, and more appropriate to use .textContent.

How to write to a <div> element using JavaScript?

I've searched around using Google and Stack Overflow, but I haven't seemed to find a answer to this. I want to write text inside a <div> element, using JavaScript, and later clear the <div> element, and write more text into it. I am making a simple text adventure game.
This is what I am trying to do:
<DOCTYPE!HTML>
<body>
<div class="gamebox">
<!-- I want to write in this div element -->
</div>
</body>
As a new user to JavaScript, how would I be able to write inside the div element gamebox? Unfortunately, my JavaScript skills are not very good, and it would be nice if you can patiently explain what happens in the code.
You can use querySelector to get a reference to the first element matching any CSS selector. In your case, a class selector:
var div = document.querySelector(".gamebox");
querySelector works on all modern browsers, including IE8. It returns null if it didn't find any matching element. You can also get a list of all matching elements using querySelectorAll:
var list = document.querySelectorAll(".gamebox");
Then you access the elements in that list using 0-based indexes (list[0], list[1], etc.); the length of the list is available from list.length.
Then you can either assign HTML strings to innerHTML:
div.innerHTML = "This is the text, <strong>markup</strong> works too.";
...or you can use createElement or createTextNode and appendChild / insertBefore:
var child = document.createTextNode("I'm text for the div");
div.appendChild(span); // Put the text node in the div
Those functions are found in the DOM. A lot of them are now covered in the HTML5 specification as well (particularly Section 3).
Select a single element with document.querySelector or a collection with document.querySelectorAll.
And then it depends, on what you want to do:
Writing Text into the div or create an Element and append it to the div.
Like mentioned getElementsByClassName is faster. Important to know it when you use this you get returned an array with elements to reach the elment you want you specify its index line [0], [1]
var gameBox = document.getElementsByClassName('gamebox')[0];
Here how you can do it
//returns array with elements
var gameBox = document.getElementsByClassName('gamebox');
//inner HTML (overwrites fsd) this can be used if you direcly want to write in the div
gameBox[0].innerHTML ='<p>the new test</p>';
//Appending when you want to add extra content
//create new element <p>
var newP = document.createElement('p');
//create a new TextNode
var newText = document.createTextNode("i'm a new text");
//append textNode to the new element
newP.appendChild(newText);
//append to the DOM
gameBox[0].appendChild(newP);
https://developer.mozilla.org/en-US/docs/Web/API/document.createElement
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName

Javascript: appendchild append div not working

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

Insert a div element as parent

I'm just wondering if the following is possible, lets say we have a dom element and we want to wrap this element in a div. So a div is inserted between the element and it's parent. Then the div becomes the element's new parent.
But to complicate things, elsewhere we have already done things like:
var testElement = document.getElementByID('testID')
where testID is a child of the element to be warapped in a div. So after we have done our insertion will testElement still be valid?
BTW: I'm not using jquery.
Any ideas?
Thanks,
AJ
You can use replaceChild [docs]:
// `element` is the element you want to wrap
var parent = element.parentNode;
var wrapper = document.createElement('div');
// set the wrapper as child (instead of the element)
parent.replaceChild(wrapper, element);
// set element as child of wrapper
wrapper.appendChild(element);
As long as you are not using innerHTML (which destroys and creates elements), references to existing DOM elements are not changed.
Assuming you are doing your manipulation using standard DOM methods (and not innerHTML) then — yes.
Moving elements about does not break direct references to them.
(If you were using innerHTML, then you would be destroying the contents of the element you were setting that property on and then creating new content)
You probably want something like:
var oldParent = document.getElementById('foo');
var oldChild = document.getElementById('bar');
var wrapper = document.createElement('div');
oldParent.appendChild(wrapper);
wrapper.appendChild(oldChild);
In pure JS you can try something like this...
var wrapper = document.createElement('div');
var myDiv = document.getElementById('myDiv');
wrapper.appendChild(myDiv.cloneNode(true));
myDiv.parentNode.replaceChild(wrapper, myDiv);
Here is another example, only the new element wraps around 'all' of its child elements.
You can change this as necessary to have it wrap at different ranges. There isn't a lot of commentary on this specific topic, so hopefully it will be of help to everyone!
var newChildNodes = document.body.childNodes;
var newElement = document.createElement('div');
newElement.className = 'green_gradient';
newElement.id = 'content';
for (var i = 0; i < newChildNodes.length;i++) {
newElement.appendChild(newChildNodes.item(i));
newChildNodes.item(0).parentNode.insertBefore(newElement, newChildNodes.item(i));
}
You will want to modify the 'document.body' part of the newChildNodes variable to be whatever the parent of your new element will be. In this example, I chose to insert a wrapper div. You will also want to update the element type, and the id and className values.

Categories

Resources