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);
Related
I need to newProductPanelContainer insie replaceclass="Replace" through JS. I'm wondering why this doesn't add anything? I'm adding an iframe to it.
Where to add
<div class="Replace">
<div class="hello">Hello</div>
<div class="hi">Hi</div>
<div class="yes">Wait</div>
</div>
Expected Output
<div class="Replace">
<div class="hello">Hello</div>
<div class="hi">Hi</div>
<div class="yes">Wait</div>
<div class="newProductPanelContainer">
<iframe id="productPanelIFrame" src="https://test.com" width="100%" height="100%" style="border: none"></iframe>
</div>
</div>
Iframe div
<script type="text/javascript">
var innerDiv = document.createElement("div");
innerDiv.className = 'newProductPanelContainer';
innerDiv.innerHTML = `<iframe id="productPanelIFrame" src="https://test.com" width="100%" height="100%" style="border: none"></iframe>`;
innerDiv.style.width = "100%";
var hello = document.getElementsByClassName("Replace");
hello.appendChild(innerDiv);
</script>
getElementsByClassName returns a collection. You can iterate over the collection and add the iframe to each element in the collection or select an (probably the first) element and add the iframe to that.
Alternatively use the querySelector method which returns the first matching element in the DOM. This is what I have done below. Note don't get confused with querySelectorAll, which returns a collection.
var innerDiv = document.createElement("div");
innerDiv.className = 'newProductPanelContainer';
innerDiv.innerHTML = `<p>I'm inserted</p><iframe id="productPanelIFrame" src="https://test.com" width="100%" height="100%" style="border: none"></iframe>`;
innerDiv.style.width = "100%";
var hello = document.querySelector(".Replace");
hello.appendChild(innerDiv);
<div class="Replace">
<div class="hello">Hello</div>
<div class="hi">Hi</div>
<div class="yes">Wait</div>
</div>
#1: You can not create an element with specific class name newProductPanelContainer with just document.createElement("newProductPanelContainer")
you can use the 2nd parameter to do that (the options) refer this
#2: You can not get the DOM of un-mount element const productPanelIFrame = document.getElementById("productPanelIFrame");
the Iframe.productPanelIFrame is the children of div.newProductPanelContainer. But you can see, its parent has not mounted yet.
Try this. It works for me
const innerDiv = document.createElement("div");
innerDiv.className = "newProductPanelContainer";
innerDiv.style.width = "100%";
const iFR = document.createElement("iframe");
iFR.id = "productPanelIFrame";
iFR.src = "https://test.com";
iFR.width = "100%";
iFR.height = "100%";
iFR.style = "border: none";
const hello = document.getElementsByClassName("Replace");
hello[0].appendChild(innerDiv);
innerDiv.appendChild(iFR);
I need to wrap children element in wrap-of-parent. Before wraping add some attributes to parent and child elements. In the code described below, everything works well if the children are one below the other in a separate row, and if they are in one row, every other child is inserted into the wrap-of-parent. Why is this happening and how to fix it?
I get:
<div id="container">
<div id="parent1">
<div id="child1"></div>
<div id="child2"></div>
<div id="wrap-of-parent1">
<div id="child3"></div>
<div id="child4"></div>
</div>
</div>
I need to get:
<div id="container">
<div id="parent1">
<div id="wrap-of-parent1">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<div id="child4"></div>
</div>
</div>
Code:
var container = document.getElementById("container");
const parentDivs = container.querySelectorAll(":scope *"); //if child elements also have child elements, to wrap in
for (let parent of parentDivs) {
// create a new div
let wrap = document.createElement('div');
wrap.id = 'wrap-of-' + parent.id;
// move the parent's children to it
let children = parent.childNodes;
for (let i = 0; i < children.length; i++) {
if (children[i].nodeType === Node.ELEMENT_NODE) {
children[i].setAttribute("data", "somedata");
wrap.append(children[i]);
}}
// and append it to the parent
parent.appendChild(wrap);
}
<div id="container">
<div id="parent1">
<div id="child1"></div><div id="child2"></div><div id="child3"></div><div id="child4"></div>
</div>
</div>
<! - If the child elements are one below the other in a separate row it works, if they are in one row it does not work ->
If you keep moving the first (index 0) entry, it will work. You need to add an offset when the wrong nodeType is encountered to skip over those ones, and if there are no child nodes then don't process the node:
var container = document.getElementById("container");
const parentDivs = container.querySelectorAll(":scope *"); //if child elements also have child elements, to wrap in
for (let parent of parentDivs) {
// create a new div
if (parent.childNodes.length > 0) {
let wrap = document.createElement('div');
wrap.id = 'wrap-of-' + parent.id;
// move the parent's children to it
let children = parent.childNodes;
const nChildren = children.length;
let offset = 0;
for (let i = 0; i < nChildren; i++) {
if (children[offset].nodeType === Node.ELEMENT_NODE) {
children[offset].setAttribute("data", "somedata");
wrap.append(children[offset]);
} else {
offset++;
}
}
// and append it to the parent
parent.appendChild(wrap);
}
}
<div id="container">
<div id="parent1">
<div id="child1"></div><div id="child2"></div><div id="child3"></div><div id="child4"></div>
</div>
</div>
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');
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>
I have this HTML template on a page:
<div id="bid_wrapper_[[bid_id]]_[[template]]">
<div class="form_item_block" id="bid_wrapper_[[bid_id]]_[[template]]">
<div id="bid_delete_[[bid_id]]_[[template]]"><img src="/images/icons/cross.png"></div>
<div id="bid_label_wrapper_[[bid_id]]_[[template]]">Bid #1</div>
<div><input type="text" name="bid_summary" id="bid_summary_[[bid_id]]_[[template]]"></div>
<div><input name="bid_price" id="bid_price_[[bid_id]]_[[template]]"></div>
</div>
</div>
I'm trying to strip out the _[[template]] text, and also replace the [[bid_id]] with a number. I tried this:
var bid_template = document.getElementById('bid_wrapper_[[bid_id]]_[[template]]').cloneNode(true)
var new_bid_id = 2
var new_oh = bid_template.outerHTML
new_oh = new_oh.replace(/_\[\[template\]\]/g, '')
new_oh = new_oh.replace(/\[\[bid_id\]\]/g, new_bid_id)
At this point if I console.log new_oh, it is exactly what I want - everything is replaced correctly. However the next lines...
var new_bid = document.createElement('div')
new_bid.outerHTML = new_oh
Nothing happens here when I try to set the outerHTML. It does work if I set the innerHTML, but I would prefer to set the outerHTML. I don't get any error messages, and I can't figure out why it's not setting the outerHTML.
I assuming the error has occurred : that 'outerHTML' property on 'Element', so element has no parent node.
if you want to create it with new div, then :
var div = document.createElement('div');
div.innerHTML = output;
document.body.appendChild(div);
if not : then try this
var bid_template = document.getElementById('bid_wrapper_[[bid_id]]_[[template]]').cloneNode(true);
var new_bid_id = 2;
var parent = document.querySelector('.parent');
var new_oh = bid_template.outerHTML;
var output = new_oh.replace(/_\[\[template\]\]/g, '');
output = output.replace(/\[\[bid_id\]\]/g, new_bid_id);
parent.innerHTML = output;
alert(output)
<div class="parent">
<div id="bid_wrapper_[[bid_id]]_[[template]]">
<div class="form_item_block" id="bid_wrapper_[[bid_id]]_[[template]]">
<div id="bid_delete_[[bid_id]]_[[template]]">
<img src="/images/icons/cross.png">
</div>
<div id="bid_label_wrapper_[[bid_id]]_[[template]]">Bid #1</div>
<div>
<input type="text" name="bid_summary" id="bid_summary_[[bid_id]]_[[template]]">
</div>
<div>
<input name="bid_price" id="bid_price_[[bid_id]]_[[template]]">
</div>
</div>
</div>
</div>
You need to insert or append the new_bid div to the document first, then reset its outerHTML.