Append a div after another div with javascript - javascript

Is there any predefined method in javascript that can append div after a div?
For example:
<div class="uploader">
<div class="file-metas">
<div class="file-name">status<span class="file-size">1kb</span></div>
<p class="state state-success">Success</p>
</div>
</div>
Now I want to insert another div with class name 'remove' after 'uploader' div.

Yeah it is possible using pure javascript
You can use insertBefore method to do so by accessing parent node of target element.
document.getElementsByClassName("uploader").parentNode
Take a look

Try this Demo
var node = document.querySelector(".uploader"),
ele = document.createElement("div");
ele.className = "remove";
ele.innerHTML = "some text";
node.parentNode.insertBefore(ele, node.nextSibling);

Vanilla JS: Supported with all the browsers:
Visualization of position names
<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->
code
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>
More info here

function appendAfter(divToAppend, siblingBefore) {
if(siblingBefore.nextSibling) {
siblingBefore.parentNode.insertBefore(divToAppend, siblingBefore.nextSibling);
} else {
siblingBefore.parentNode.appendChild(divToAppend);
}
}

The following example demonstrates what you are trying to achieve using plain JavaScript:
<html>
<head>
<script>
function addNewDiv() {
var newDiv = document.createElement('div');
var label = document.createTextNode(" - new div - ");
var elements = document.getElementsByClassName('uploader');
var uploaderDiv = elements[0];
newDiv.appendChild(label);
elements[0].insertBefore(newDiv, uploaderDiv.children[0]);
}
</script>
</head>
<body>
<div class="uploader">
<div class="file-metas">
<div class="file-name">status<span class="file-size">1kb</span>
</div>
<p class="state state-success">Success</p>
</div>
</div>
<input type="button" onClick="addNewDiv()" value="Add new Div" />
</body>
</html>

Related

How to add an HTML element found by ID to the body?

I want to add an DOM element that is found by ID into the body tag and remove all ewxisting body nodes.
My solution does not work:
var ele = document.getElementById("email");
document.body.innerHTML = ele;
This:
document.body.innerHTML = ele;
Will interpret ele as a string and write that string to the document body. That string is going to be something like "[object HTMLDivElement]" (may differ by browser).
and remove all ewxisting body nodes
It sounds like you're looking for document.body.replaceChildren() then? For example:
var ele = document.getElementById("email");
document.body.replaceChildren(ele);
<div>test 1</div>
<div id="email">test 2</div>
<div>test 3</div>
There are a few options.
Option 1 : clear the content of <body> and append your element as a child.
var el = document.getElementById("one");
document.body.innerHTML = ''; // Clears the body inner HTML
document.body.appendChild(el) // Appends your element as a child
<div id="one">
HELLO
</div>
GOOD BYE CONTENT
Option 2 : Replace children of <body> with your element.
var el = document.getElementById("one");
document.body.replaceChildren(el); // Replace the body content by your element
<div id="one">
HELLO
</div>
GOOD BYE CONTENT
With append or replaceChildren you can reach this.
const tag = document.querySelector('#email');
const w = document.createElement('div');
w.append(tag)
document.querySelector('body').innerHTML = '';
document.querySelector('body').append(w);
<html>
<head>Head</head>
<body>
<h1>body</h1>
<div id="email"> EMAIL </div>
</body>
</html>
const tag = document.querySelector('#email');
document.querySelector('body').replaceChildren(tag);
<html>
<head>Head</head>
<body>
<h1>body</h1>
<div id="email"> EMAIL </div>
</body>
</html>

javascript replace node and all of it childs with anothe code

How can you replace HTML tag with all tags branching inside using Javascript with other HTML code?
example:
<div class="a">
<div class="sub-a1">
<div class="sub-a12">
</div>
</div>
<div class="sub-a2">
<div class="sub-b">
</div>
</div>
I wanna replace all tags from tag div class 'a' including all sub nodes with another code.
is that's possible?
please help me.
const target = document.querySelector(".a");
target.innerHTML = //place your html here as string
Yes, this is possible. If you want to keep the div.a elements and just change the "subnodes" you have to use innerHTML in stead of outerHTML.
const divs = [...document.getElementsByClassName("a")]; //make a copy of the HTML collection so that they can be removed without being removed in the array
const newElement = "<h1>Replaced Element</h1>"; //this is your replacement element
for (let i = 0; i < divs.length; i++) { // loop through all the divs
divs[i].outerHTML = newElement; // set the outer html for the div to the replacement elemzent
}
You can do with .replaceWith() with a valid HTML code.
function replace() {
var para = document.createElement("P"); // Create a <p> element
para.innerText = "This is a paragraph"; // Insert text
document.querySelector(".a").replaceWith(para);
}
<div class="a">
<div class="sub-a1">
<div class="sub-a12">
<h4>Sample content1</h4>
</div>
</div>
<div class="sub-a2">
<div class="sub-b">
<h4>Sample content2</h4>
</div>
</div>
</div>
<button onclick="replace();"/>Click to Replace</button>

Show and append a div

I'm writing a HTML code where there are 3 divs - and in the mainDiv2, there is this another div that is hidden. When I click on the mainDiv2, I want to unhide the hiddenDiv(this I'm able to do it). As well as I want this hiddenDiv to be shown in mainDiv1 as a child.
Here is my code.
<div class="mainDiv1">
This si a main div content
</div>
<div class="mainDiv2" onclick="showhiddenDiv()">
This is a sub div content
<div class="hiddenDiv" id="hiddenDiv" style="display:none">
Hello World
</div>
</div>
JS
function showhiddenDiv(){
document.getElementById('hiddenDiv').style.display="block";
}
please let me know how can I do this.
Here is a working fiddle. https://jsfiddle.net/8pj3uvfn/1/
Thanks
You can use appendChild like below
function showhiddenDiv() {
var hiddenDiv = document.getElementById('hiddenDiv');
var mainDiv1 = document.getElementsByClassName('mainDiv1')[0];
hiddenDiv.style.display = "block"
mainDiv1.appendChild(hiddenDiv)
}
<div class="mainDiv1" id="mainDiv1">
This is a main div content
</div>
<div class="mainDiv2" onclick="showhiddenDiv()">
This is a sub div content
<div class="hiddenDiv" id="hiddenDiv" style="display:none">
Hello World
</div>
</div>
As well as I want this hiddenDiv to be shown in mainDiv1 as a child.
You need to clone the hiddenDiv and put it in mainDiv1.
So modify your method as
function showhiddenDiv(){
var hiddenNode = document.getElementById('hiddenDiv');
hiddenNode.style.display="block";
var copyHiddenNode = hiddenNode.cloneNode( true );
copyHiddenNode.id += "_1"; //change the id so that ids are not duplicated
document.getElementById("mainDiv1").appendChild( copyHiddenNode );
}
You could use appendChild
function showhiddenDiv(){
var hiddenDiv = document.getElementById('hiddenDiv');
document.getElementsByClassName('mainDiv1')[0].appendChild(hiddenDiv);
hiddenDiv.style.display="block";
}
Demo
Assuming that you have set the id attributes of the divs properly,
function showhiddenDiv(){
var hiddenDiv = document.getElementById('hiddenDiv'); //Get the reference
document.getElementById('mainDiv1').appendChild(hiddenDiv) //Chenge the DOM order (you don't have to clone)
hiddenDiv.style.display="block"; //Unhide
}
<div class="mainDiv1">
This si a main div content
</div>
<div class="mainDiv2" onclick="document.getElementById('hiddenDiv').style.display = 'block'">
This is a sub div content
<div class="hiddenDiv" id="hiddenDiv" style="display:none">
Hello World
</div>
</div>

Setting Width of <div> with Javascript

I have a <table> which is dynamically created so the width is unknown. I'm trying to add horizontal scroll bars to the top and bottom of it. My current code...
<div class="wrapper1">
<div class="div1" width="<script type=\"text/javascript\">document.write(mytext);</script>">
</div>
</div>
<div class="wrapper2">
<div class="div2">
<table id="table_width">
*table content goes here*
</table>
</div>
</div>
<script type="text/javascript">
$(function(){
$(".wrapper1").scroll(function(){
$(".wrapper2")
.scrollLeft($(".wrapper1").scrollLeft());
});
$(".wrapper2").scroll(function(){
$(".wrapper1")
.scrollLeft($(".wrapper2").scrollLeft());
});
});
var mytext = document.getElementById("table_width").offsetWidth; //Method 1
var mytext = document.getElementById("table_width").style.width = width + 'px'; //Method 2
</script>
In the last few lines, I've tried two different methods to set the width of the containing <div> to be mytext.
Any ideas why either method isn't working? BTW, I'm not trying both methods at the same time the way it's shown here.
To find the width of an element you need to use window.getComputedStyle followed by getPropertyValue on that returned value. What you are doing now only gives you the CSS value which is not set.
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
The problem could be this.
The script you have written to find mytext is being executed after the table is created. But by the time the div is created value of mytext is not known. So I would recommend doing this.
<!DOCTYPE html>
<div class="wrapper1">
<div id="div1">
</div>
</div>
<div class="wrapper2">
<div class="div2">
<table>
*table content goes here*
</table>
</div>
<script type="text/javascript">
$(function(){
$(".wrapper1").scroll(function(){
$(".wrapper2")
.scrollLeft($(".wrapper1").scrollLeft());
});
$(".wrapper2").scroll(function(){
$(".wrapper1")
.scrollLeft($(".wrapper2").scrollLeft());
});
});
var mytext = document.getElementById("table_width").offsetWidth; //Method 1
var mytext = document.getElementById("table_width").style.width ; //Method 2
document.getElementById('div1').width = mytext;
</script>
</html>
The above code changes the width of the div after finding the value of mytext.
I ended up using parts of both of the suggested answers for this question. After a lot of fiddling, I ended up with this for the final Javascript...
var elem = document.getElementById("table_width");
var mytext = window.getComputedStyle(elem,null).getPropertyValue("width");
$('#div1').css({'width':mytext});
$('#div1').css({'overflow': 'scroll'});

Modifying DOM of a webpage

The structure of a webpage is like this :-
<div id='abc'>
<div class='a'>Some contents here </div>
<div class='b'>Some other contents< </div>
</div>
My aim is to add this after the class a in above structure.
<div class='a'>Some other contents here </div>
So that final structure looks like this :-
<div id='abc'>
<div class='a'>Some contents here </div>
<div class='a'>Some other contents here </div>
<div class='b'>Some other contents< </div>
</div>
Can there be a better way to do this using DOM properties. I was thinking of naive way of parsing the content and updating.
Please comment if I am unclear in asking my doubt !
Create the desired element, give it the desired attributes, children, innerHTML, etc, and then append it:
var parent = document.getElementById('abc'),
ele = document.createElement('div');
ele.setAttribute('class', 'a');
ele.innerHTML = "Some other contents here";
parent.appendChild(ele);​
Fiddle
You can be lazy and just set the innerHTML of #abc, but in my opinion this method is more flexible.
I think this is what you are looking for http://jsfiddle.net/cExRS/
The code is this one
element = document.getElementById('abc');
element.innerHTML = "<div class='a'>Some other contents here </div>" + element.innerHTML;
You should really try jquery, it makes things a lot easier
Liked pointed out there's answer for prepending, Insert sibling node in JS
and How can I implement prepend and append with regular JavaScript?
<html>
<head>
<script type="text/javascript">
function add(myClass) {
var root = document.getElementById('abc');
var last = null;
for (var i = 0; i < root.childNodes.length; i++) {
var child = root.childNodes[i];
if (!child.className) continue;
var pat = new RegExp(myClass,'g');
var m = pat.exec(child.className);
if (!m) {
if (!last) continue;
var div = document.createElement('div');
div.appendChild(document.createTextNode('After A content'));
root.insertBefore(div, last.nextSibling);
break;
}
last = child;
}
}
</script>
</head>
<body>
<div id='abc'>
<div class='d'>Some contents here </div>
<div class='b'>Some other contents </div>
<div class='a'>Content A</div>
<div class='a'>Content A1</div>
<div class='a'>Content A2</div>
<div class='a'>Content A3</div>
<div class='b'>Some other contents </div>
</div>
Add div
</body>
</html>
This question is a duplicate :s
How can I implement prepend and append with regular JavaScript?
It's called prepending

Categories