JQuery append multiple child content to parent element - javascript

I have to add multiple child content to parent element dynamically using jquery , here is the example code I am referring https://github.com/linslin/pagingSlider ,
The code is so,
<div id="wrapper">
<div class="slidepage-container myPageContainerClass">
<div id="badges-slidepage-1" page="1" class="psPage center current">
<div class="content">
<h2>Page 1</h2>
</div>
</div>
<div id="badges-slidepage-2" page="2" class="psPage right">
<div class="content">
<h2>Page 2</h2>
</div>
</div>
<div id="badges-slidepage-3" page="3" class="psPage right">
<div class="content">
<h2>Page 3</h2>
</div>
</div>
<div id="badges-slidepage-4" page="4" class="psPage right">
<div class="content">
<h2>Page 4</h2>
</div>
</div>
</div>
I am able to add child elements to parent
var parentwrapper= $("<div/>").attr('id', 'wrapper');
var firstDiv= $("<div/>").addClass("slidepage-container myPageContainerClass");
var firstPage= $("<div/>").attr("id", "badges-slidepage-1").attr("page", "1").addClass("psPage center current");
var contentDiv= $("<div/>").addClass("content");
var firstcontent= $("<div/>").addClass("dealerNextTo dealerRectangleBox rectangleTopLeft").text("promptText");
var secondPage = $("<div/>").attr("id", "badges-slidepage-2").attr("page", "2").addClass("psPage right");
var secondContent= $("<div/>").addClass("dealerNextTo dealerRectangleBox rectangleTopLeft").text("promptText");
var myFinalVar = $(parentwrapper).append(firstDiv).append(firstPage).append(contentDiv).append(firstcontent).append(secondPage).append(secondContent);
$(myFinalVar).appendTo('body');
but it is adding to firstpage ContentDiv only,
How to achieve it. Any ideas? (I'm new to Jquery)

The problem is that you are chaining appends to add the elements you created like this:
var myFinalVar = $(parentwrapper).append(firstDiv).append(firstPage).append(contentDiv)
.append(firstcontent).append(secondPage).append(secondContent);
When you chain appends, elements do not get added to the previous element in the chain, they are all added directly to the first element. In your code, you are adding all elements as direct children of parentwrapper.
You need to add each child (or set of siblingss) to their parent separately, e.g. you need to add only firstDiv to parentwrapper:
var myFinalVar = $(parentwrapper).append(firstDiv);
firstPage and secondPage are being appended to the same parent, so you can chain those like this:
$(firstDiv).append(firstPage).append(secondPage); // appending to the SAME parent
Working Example:
var parentwrapper = $("<div/>").attr('id', 'wrapper');
var firstDiv = $("<div/>").addClass("slidepage-container myPageContainerClass");
var firstPage = $("<div/>").attr("id", "badges-slidepage-1").attr("page", "1").addClass("psPage center current");
var contentDiv = $("<div/>").addClass("content");
var firstcontent = $("<div/>").addClass("dealerNextTo dealerRectangleBox rectangleTopLeft").text("Page 1 content div");
var secondPage = $("<div/>").attr("id", "badges-slidepage-2").attr("page", "2").addClass("psPage right");
var secondContent = $("<div/>").addClass("dealerNextTo dealerRectangleBox rectangleTopLeft").text("Page 2 content div");
var myFinalVar = $(parentwrapper).append(firstDiv);
// chain appends to add to the SAME div
$(firstDiv).append(firstPage).append(secondPage);
$(firstPage).append(contentDiv);
$(contentDiv).append(firstcontent);
$(secondPage).append(secondContent);
$(myFinalVar).appendTo('body');
#wrapper { padding: 10px; background: #eee; }
.slidepage-container.myPageContainerClass,
.content,
.psPage,
.dealerNextTo{ border: 1px solid blue; padding: 10px;}
.psPage { margin-bottom:20px; }
.rectangleTopLeft { background: lightblue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
FYI you also seem to be missing an element on the secondPage elements - it doesn't have a .content div.

Here is what you may want to try:
// append first content to contentDiv
contentDiv.append(firstcontent);
// append contentDiv to firstPage
firstPage.append(contentDiv);
// append firstPage to firstDiv
firstDiv.append(firstPage);
// again append secondContent to secondPage
secondPage.append(secondContent);
firstDiv.append(secondPage);
var myFinalVar = $(parentwrapper).append(firstDiv);
$(myFinalVar).appendTo('body');

Related

How to wrap same classes inside one parent div using javascript

I have some div with 2 different classes like the one below
<div class = "leftAlign">One</div>
<div class = "leftAlign">Two</div>
<div class = "leftAlign">Three</div>
<div class = "leftAlign">Four</div>
<div class = "rightAlign">Five</div>
<div class = "rightAlign">Six</div>
<div class = "rightAlign">Seven</div>
and I want to wrap all the classes with leftAlign class inside a parent div, something like this
<div class = "wrapper">
<div class = "leftAlign">One</div>
<div class = "leftAlign">Two</div>
<div class = "leftAlign">Three</div>
<div class = "leftAlign">Four</div>
<div>
<div class = "rightAlign">Five</div>
<div class = "rightAlign">Six</div>
<div class = "rightAlign">Seven</div>
This is what I have done, but it does not seems to work
let target = document.querySelectorAll('leftAlign');
let wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
target.parentNode.insertBefore(wrapper, target);
wrapper.appendChild(target);
here you go
var lefties = document.querySelectorAll('.leftAlign');
var first = lefties[0];
var div = document.createElement('div');
div.classList.add('contain');
first.replaceWith(div);
lefties.forEach(d => div.appendChild(d));
.rightAlign {
text-align:right;
}
.leftAlign {
text-align:left;
background:red;
}
.contain>.leftAlign {
background:transparent;
}
<div class="leftAlign">One</div>
<div class="leftAlign">Two</div>
<div class="leftAlign">Three</div>
<div class="leftAlign">Four</div>
<div class="rightAlign">Five</div>
<div class="rightAlign">Six</div>
<div class="rightAlign">Seven</div>
create the parent element
const container = document.createElement('div');
container.setAttribute('class', 'wrapper');
get the child elements you want the above parent to encapsulate
const children = document.querySelectorAll('.leftAlign');
loop through children and append to parent
children.forEach(function(child) {
container.appendChild(child);
});
append container to the area in the dom you wish to place it (e.g. if body)
document.body.appendChild(container);

Appendchild only works on last element

I am trying to create an element in JavaScript and apply it to all elements by class name. For this example I will use a paragraph for ease. The purpose of creating an element by JavaScript however is because I want to create a different element later on in my code.
In the code I am using, only the last element of the array of elements will contain the element created by the JavaScript. Could anyone explain why this is happening and what I could do to solve the problem accordingly to my requirement? I am trying to apply a whole element inside another element (so not just a value or property of a paragraph element).
My code:
//Creating my element:
let myElement = document.createElement("p");
/*let text = document.createTextNode("test");
myElement.appendChild(text);*/ //<-- Enable following to see text in result or check developer console for added paragraphs
//Single example:
let ele = document.getElementById("bar");
ele.appendChild(myElement);
//Not working...:
//Now class:
let eles = document.getElementsByClassName("foo");
for (i = 0; i < eles.length; i++) {
//eles[i].innerHTML = "abc";//<-- Does work (but hardcoded)?
//eles[i].innerHTML = myElement;//<-- returns "[object HTMLParagraphElement]"?
eles[i].appendChild(myElement); //<!-- Does work only for last element in array?
}
<div class="foo" id="bar">
</div>
<div class="foo">
</div>
<div class="foo">
</div>
<div class="foo">
<!-- Only this one will obtain the the paragraph element? -->
</div>
JSFiddle
You need to use cloneNode of element <p>, because appendChild moves it from its current position to the new position. See documentation
//Creating my element:
const myElement = document.createElement("p");
myElement.innerHTML = 'paragraph';
//Single example:
const ele = document.getElementById("bar");
ele.appendChild(myElement.cloneNode(true));
//Now class:
const eles = document.getElementsByClassName("foo");
for (let i = 0; i < eles.length; i++) {
eles[i].appendChild(myElement.cloneNode(true));
}
.foo {
border: 1px solid #333;
}
.foo p {
font-weight: bold;
}
<div class="foo" id="bar">
bar:
</div>
<div class="foo">
foo1
</div>
<div class="foo">
foo2
</div>
<div class="foo">
foo3
</div>
Your <p> element is appended only to the last because it is assigned to the myElementvariable. And because that variable is declared before your loop, each iteration will move the <p> tag through all your <div.foo>.
But if you declare your paragraph inside your for loop, a new one is created and appended to each of your blocks, because there are all different elements.
let eles = document.getElementsByClassName("foo");
for (i = 0; i < eles.length; i++) {
let myElement = document.createElement("p");
myElement.innerText = 'I am a paragraph.';
eles[i].appendChild(myElement);
}
<div class="foo" id="bar">
</div>
<div class="foo">
</div>
<div class="foo">
</div>
<div class="foo">
</div>

How to add a div between two divs by Javascript

I am using wordpress and I want to add some html code on page using Javascript. I don't want to make child theme then edit php files. It is risky and I don't know about php.
I want to add a sibling div. This is an example code as default.
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
Now I want to add my custom div and its inside html between both div1 and div2.
<div class="mydiv">
<div class="mydivinside">
Text
</div>
</div>
Please let me know how is it possible using Javascript.
There are (at least) two ways, the first:
// document.querySelector() finds, and returns, the first element
// matching the supplied selector (or null, if no element is found):
var el1 = document.querySelector('.div1');
// here we create an adjacent element from the string of HTML,
// the 'afterend' argument states that this adjacent element
// follows the el1 node, rather than preceding it or appearing
// within:
el1.insertAdjacentHTML('afterend', '<div class="mydiv"><div class="mydivinside">Text</div></div>');
var div1 = document.querySelector('.div1');
div1.insertAdjacentHTML('afterend', '<div class="mydiv"><div class="mydivinside">Text</div></div>');
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
And the second where you first create that <div> to be inserted, and then use parentNode.insertBefore():
var htmlString = '<div class="mydiv "><div class="mydivinside">Text</div></div>',
// here we create a <div> element:
div = document.createElement('div'),
// we retrieve the element after which the new
// element should be inserted:
div1 = document.querySelector('.div1');
// assign the supplied HTML string to the innerHTML of the
// created element:
div.innerHTML = htmlString;
// and use parentNode.insertBefore to insert the desired element
// (the first argument) before the element identified in the
// second argument, which is the nextSibling of the found
// 'div1' element:
div1.parentNode.insertBefore(div.firstChild, div1.nextSibling);
var htmlString = '<div class="mydiv "><div class="mydivinside">Text</div></div>',
div = document.createElement('div'),
div1 = document.querySelector('.div1');
div.innerHTML = htmlString;
div1.parentNode.insertBefore(div.firstChild, div1.nextSibling);
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
References:
document.createElement().
document.querySelector().
Element.insertAdjacentHTML().
Node.firstChild.
Node.insertBefore().
Node.nextSibling.
Node.parentNode.
Use Node#insertBefore method.
// create a div element
var div = document.createElement('div');
// set class name
div.className = 'mydiv';
// set html contents
div.innerHTML = ' <div class="mydivinside"> Text </div>';
// get .div2 element
var ele = document.querySelector('.div2');
// insert before the .div2 element by getting
// its parent node
ele.parentNode.insertBefore(div, ele);
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
You can just use the before method to append a div between both div1 and div2. Here is the example:
$('.div2inside').before("<div class='mydiv'><div class='mydivinside'>Text</div></div>");
You could do something like this?
var firstDiv = document.getElementById('div1');
firstDiv.parentNode.insertBefore(document.getElementById('new-div'), firstDiv.nextSibling);
This however assumes that your new-div is already in the dom.
EDIT: to create a the new-div on the fly you can use #david-thomas's solution https://stackoverflow.com/a/41425079/1768337
This link will be helpfull to get the above result.
https://plainjs.com/javascript/manipulation/insert-an-element-after-or-before-another-32/

Add all elements after first element to a div by using javascript (No jQuery)

I have the following html
<div id="main">
<aside id="list"><p>sometext</p></aside>
<aside id="list-2"><p>sometext</p></aside>
<aside id="list-3"><p>sometext</p></aside>
<aside id="list-4"><p>sometext</p></aside>
</div>
I want to use javascript to make it look like :
<div id="main">
<aside id="list"><p>sometext</p></aside>
<div id="wrap">
<aside id="list-2"><p>sometext</p></aside>
<aside id="list-3"><p>sometext</p></aside>
<aside id="list-4"><p>sometext</p></aside>
</div>
</div>
I have tried insertAdjacentHTML and innerHTML methods :
widgets = document.getElementById('main');
widgets.innerHTML = "<div class='box-class'>" + widgets.innerHTML + "</div>";
But this adds wrapper over "list" too.
There are two big problems with the code you said you tried (three if widgets isn't declared anywhere):
widgets = document.getElementById('main');
widgets.innerHTML = "<div class='box-class'>" + widgets.innerHTML + "</div>";
Using strings means the browser has to go through the elements, build an HTML string for them, and return that string to JavaScript; then when you assign to innerHTML it has to destroy the elements that are already there and build new replacement ones by parsing the HTML string. This will wipe out any event handlers or similar attached to the elements. (Of course, if there aren't any, it doesn't matter much.)
That wraps all of the children, not just the ones after the first child.
(It also wraps them in <div class='box-class'>, not <div id="wrap">, but...)
On all modern browsers, elements have a children list you can use for this. Then just create a wrapper, move the children other than the first into it, and append it.
var main = document.getElementById("main");
var wrapper = document.createElement("div");
wrapper.id = "wrap";
while (main.children.length > 1) {
// Note: Appending the element to a new parent removes it from its original
// parent, so `main.children.length` will decrease by 1
wrapper.appendChild(main.children[1]);
}
main.appendChild(wrapper);
Example:
var main = document.getElementById("main");
var wrapper = document.createElement("div");
wrapper.id = "wrap";
while (main.children.length > 1) {
wrapper.appendChild(main.children[1]);
}
main.appendChild(wrapper);
#wrap {
border: 1px solid blue;
}
<div id="main">
<aside id="list">
<p>sometext</p>
</aside>
<aside id="list-2">
<p>sometext</p>
</aside>
<aside id="list-3">
<p>sometext</p>
</aside>
<aside id="list-4">
<p>sometext</p>
</aside>
</div>
Side note: In your markup, you have </div> where you want </aside>.

Issue using childNodes to process the childnodes javascript

I am trying to make display none for all the child nodes of a div. It works well with getElementsByTagname('*')
My Markup
<div id="container">
<div id="child1"></div>
<div id"child2">
<div id="inner-child"></div>
</div>
</div>
I would like to manipulate the display property of only the child1, child2.
function hideAllChildren(){
var elem = document.getElementById("container");
var children = elem.childNodes;
alert("children " + children.length)
for (i=0; i < children.length ;i++)
{
children[i].style.display="none";// Error - children[i].style undefined
}
}
Can you figureout what the issue could be ?
Not all the child nodes are elements, some are text nodes in some browsers and text nodes don't have a style property. Trying to access a property of a non-existant property throws an error.
Either test the node type or that the node has a (non-falsey value for its) style property first:
if (children[i].style) {
children[i].style.display="none";
}
However, you may find it much better to use a class and appropriate CSS rule and just add it to the parent element.
e.g.
<style type="text/css">
.hideAll * {
display: none;
}
</style>
</script type="text/javascript">
<button onclick="
document.getElementById('d0').className = 'hideAll';
">Hide all</button>
<button onclick="
document.getElementById('d0').className = '';
">Show all</button>
<div id="d0">Here is the div
<ul>
<li class="item">apple
<li class="item">orange
<li class="item">banana
</ul>
</div>
Why do you want to hide all the child nodes.
Where you can hide the parent and all the child will automatically hide.
So it will be simply:
function hideAllChildren(){
var elem = document.getElementById("container");
//alert("children " + children.length)
elem.style.display="none";
}
try this
<div id="container">container
<div id="child1">child1</div>
<div id"child2">Child 2
<div id="inner-child">inner-child</div>
</div>
</div>
<div id="clickme">Click me</div>
/// java script
$('#clickme').click(function() {
hideAllChildren();
});
function hideAllChildren(){
var elem = document.getElementById("container");
var children = elem.childNodes;
alert("children " + children.length)
$('#container').hide();
}

Categories

Resources