How to add a div between two divs by Javascript - 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/

Related

Change Class Content to href

<div class="container">
<span class="text1">test</span>
<span class="text2">test</span>
</div>
I want to change "text2" to a href in a javascript inside my function like this:
var x=document.getElementsByClassName("text2"); // Find the elements
x.innerHTML="<a href='https://test.com'>test</a>"; // Change the content
so the content of "text2" changes to a hyperlink called "test" which refers to "https://test.com"
you can do it like so:
var element = document.querySelector(".text2"); // Find the first element with the class text2
element.innerHTML = "test"; // Change the content including all HTML elements that might be in there to the value specified escaping the " character
<div class="container">
<span class="text1">test</span>
<span class="text2">test</span>
</div>
the problem was you didn't escaped the " character
you can do it also without the escaping like that:
var element = document.querySelector(".text2"); // Find the first element with the class text2
element.innerHTML = "<a href='https://test.com'>test</a>"; // Change the content including all HTML elements that might be in there to the value specified
<div class="container">
<span class="text1">test</span>
<span class="text2">test</span>
</div>
Not quite sure which approach you need. So here are both:
HTML
<div class="container">
<span class="text1">test</span>
<span class="text2">test</span>
</div>
Approach A - Replace the inner html of the target
document.querySelector(".text2").innerHTML = "<a href='https://test.com'>test</a>";
Approach B - Replace the Span with Anchor
var target = document.querySelector(".text2");
if (target) {
var anchor = document.createElement("a");
anchor.setAttribute("href", "https://www.test.com");
anchor.innerHTML = target.innerHTML;
target.replaceWith(anchor);
}

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>

Wrap two elements in HTML with javascript

I have this code that is generated by php:
<div class="fusion-post-content post-content">
<h2 class="blog-shortcode-post-title"></h2>
<p class="fusion-single-line-meta"></p>
<div class="fusion-post-content-container"></div>
</div>
I need to wrap two elements by using javascript so the code would look like this:
<div class="fusion-post-content post-content">
<div class="class">
<h2 class="blog-shortcode-post-title"></h2>
<p class="fusion-single-line-meta"></p>
</div>
<div class="fusion-post-content-container"></div>
</div>
This will do what you want. Isn't it better to change the code on server-side??
// Select the first element found
var parent = document.querySelector('.fusion-post-content');
console.log('Old child-length', parent.children.length);
console.log('Old:', parent.innerHTML);
// *You don't need the timeout
setTimeout(function () {
var h2 = parent.firstElementChild;
var p = parent.firstElementChild.nextElementSibling;
// Remove cildren
parent.removeChild(h2);
parent.removeChild(p);
// Insert the new child
parent.insertAdjacentHTML('afterbegin', '<div class="class"></div>');
// Insert the other children (old) in the new child
parent.firstElementChild.insertAdjacentElement('beforeend', h2);
parent.firstElementChild.insertAdjacentElement('beforeend', p);
// Gets one less, since we put to children in one (3 - 1 = 2)
console.log('New child-length', parent.children.length);
console.log('New:', parent.innerHTML);
}, 500);
<div class="fusion-post-content post-content">
<h2 class="blog-shortcode-post-title"></h2>
<p class="fusion-single-line-meta"></p>
<div class="fusion-post-content-container"></div>
</div>

Before, not replace

Trying to figure out how should I put a span before my_div_class and not to replace all of it. Now it replaces the div, but I don't want to do it. I assume it's something like :before but have no idea how to use it.
<script>
{
var x = document.getElementsByClassName("my_div_class");
x[0].innerHTML = "<span style='color:#ff0000;'>Hello World!<span>";
}
</script>
Use insertAdjacentHTML:
var x = document.getElementsByClassName("my_div_class");
var html = '<span style="color:#ff0000;">Hello World!<span>';
x[0].insertAdjacentHTML('beforebegin', html);
<div class="my_div_class">Hallo</div>
If you want to add the span before the current content of the div, use:
x[0].innerHTML = "<span style='color:#ff0000;'>Hello World!</span> " + x[0].innerHTML;
Notice that you have several errors in your code:
You didn't close the span tag properly.
You don't need those curly brackets.
You may want to add a space at the end of the span to separate it from the current content of the div.
Try this:
var x = document.getElementsByClassName("my_div_class");
x[0].innerHTML = "<span style='color:#ff0000;'>Hello World!</span> " + x[0].innerHTML;
<div class="my_div_class">first div</div>
<div class="my_div_class">another div</div>
<div class="my_div_class">yet another div</div>
<div class="my_div_class">second div</div>
<div class="my_div_class">third div</div>

can't change outerHTML with javascript

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.

Categories

Resources