Better ways of inserting simple HTML into a div using JavaScript - javascript

I'm always seeming to have to insert HTML into a load of divs using jQuery, but I prefer JavaScrip and wonder if anybody has any better ways of doing it. See the typical example below:
let boxes = document.querySelectorAll('.main-editor-output');
for (let box of boxes) {
console.log(box);
$( "<p>Test</p>" ).prependTo(box);
}
.main-editor-output {
border: 1px solid black;
margin-top: 10px;
min-height: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div id='parent'>
<div class="main-editor-output"></div>
<div class="main-editor-output"></div>
</div>
Here I'm just using a simple line of jQuery to insert HTML into the test divs. I could do it using javascript, but that would require too many lines of code. Does anyone have any better ways of doing this?
Thanks for any ideas!
Codepen: https://codepen.io/ns91/pen/GRKGwZP

you can use insertAdjacentHTML
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
in your example it would be box.insertAdjacentHTML('afterbegin', '<p>Test</p>');
demo:
let boxes = document.querySelectorAll('.main-editor-output');
for (let box of boxes) {
console.log(box);
box.insertAdjacentHTML('afterbegin', '<p>Test</p>');
}
.main-editor-output {
border: 1px solid black;
margin-top: 10px;
min-height: 1em;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<div id='parent'>
<div class="main-editor-output">
Existing text
</div>
<div class="main-editor-output">
</div>
</div>

In Vanilla JavaScript you can:
create an item with createElement
append it with appendChild
prepend it with insertBefore
For example, the following code will create two inputs, assign them an id and a value, then append the first and prepend the second inside a div with id container:
let container = document.getElementById('container');
let input1 = document.createElement('input');
input1.id = 'input1';
input1.value = 'I am input 1!';
container.appendChild(input1);
let input2 = document.createElement('input');
input2.id = 'input2';
input2.value = 'I am input 2!';
container.insertBefore(input2, input1);
<div id="container"></div>

You can use $element.innerHTML, which is a native JavaScript property of elements.
It works similar to the jQuery element method $element.html().
<div id="test">Pre Text</div>
<script> document.querySelector('#test').innerHTML = 'Post Text'; </script>

I don't know if it's exactly what you're looking for, but in any case you can use document.createElement to create the child element, and add it to the parent element using the prepend method:
let boxes = document.querySelectorAll('.main-editor-output');
for (let box of boxes) {
console.log(box);
let element = document.createElement("p");
element.append("Test");
box.prepend(element);
}
.main-editor-output {
border: 1px solid black;
margin-top: 10px;
min-height: 1em;
}
<head>
</head>
<div id='parent'>
<div class="main-editor-output">
</div>
<div class="main-editor-output">
</div>
</div>

Related

Is it possible to remove an html element and keep your children with javascript?

I have the following structure .. I would like to remove div.son but keepdiv.grandson, is that possible ?! or changing your <tag> would also be a solution .. ex: changing from <fieldset> to a <div>, remembering that I do not have access to HTML, every change must be done using ** javascript **!
<div class="father">
<fieldset class="son">
<div class="grandson">Content here</div>
<div class="grandson">Content here</div>
<div class="grandson">Content here</div>
<div class="grandson">Content here</div>
</fieldset>
</div>
I tried to use the removeChild () function of ** javascript **, but it removes the entire element.
It's possible with vanilla JavaScript by deep cloning the node of grandson before removing anything else. and then appending it back to the parent. Of course if you want to place it somewhere else, you need to append needed logic of DOM traversing. (CSS section is only for visual validation of the result)
const grandson = document.querySelector('.grandson');
const father = grandson.closest('.father');
const clonedGrandson = grandson.cloneNode(true);
father.querySelector('.son').remove();
father.appendChild(clonedGrandson);
.father {
background-color: red;
padding: 20px;
}
.son {
background-color: blue;
padding: 20px;
}
.grandson {
background-color: green;
padding: 20px;
}
<div class="father">
<fieldset class="son">
<div class="grandson">
<p>Save me</p>
</div>
</fieldset>
</div>
You may take a look at this answer, try to use the search bar next time.
https://stackoverflow.com/a/170056/10944905
In case you just want to jump all over the answer.
var cnt = $(".remove-just-this").contents();
$(".remove-just-this").replaceWith(cnt);

How do I append an existing html element to another element?

I want to append multiple copies of div with id hello into the div with id container. How do I do this using javascript?
<div id="container">
</div>
<div id="hello">
<p>Hello</p>
</div>
Using cloneNode and appendChild.
Since ids should be unique in a document, I switched things to use a class hello instead.
function makeCopy() {
const target = document.getElementById("container");
const source = document.querySelector(".hello");
const clone = source.cloneNode(true);
target.appendChild(clone);
}
.hello {
padding: 3px;
margin: 3px;
border: 1px dotted orange;
}
<div id="container">
This is the container.
</div>
<button onclick="makeCopy()">Add a clone of hello above</button>
<div class="hello">
<p>Hello</p>
</div>
https://www.w3schools.com/jsref/met_node_appendchild.asp
check this out, it will solve your problem, BUT use a class for the tag not an ID. IDs are unique, a class is for multiple elements.
you can call class in CSS like this
.className {
/*CODE*/
}
you can use append() method:
$(document).on('click', function(){
$('#container').append( $('#hello') );
});

Wrap multiple elements in new div without destroying them - Javascript DOM manipulation

I am trying to 'de-jquery' some code.
I have a div like so:
<div id="main">
<div class="blue"></div>
<div class="green"></div>
<div class="yellow"></div>
</div>
And I wish to insert a wrapper div around all elements except the first. The full number of elements is undetermined, there could be more.
The current solution uses jquery nextAll and wrapAll to produce the following result:
HTML
<div id="main">
<div class="blue"></div>
<div class="wrapper">
<div class="green"></div>
<div class="yellow"></div>
</div>
</div>
jQuery
$(".blue").each(function() {
$(this)
.nextAll()
.wrapAll('<div class="wrapper"></div>');
});
How can I remove all jQuery from this and make it vanilla?
I cannot see any wrap type methods. I could grab the HTML that doesn't have index of [0] and insert it into a new div, then insert that after .blue but that seems messy. Is there a better way?
edit: oh you just want to skip the first item…
skip this solution to the new solution at the bottom.
// this is how you can grab a node.
// alternatively you could use document.querySelectorAll
// (wich will be similar to how $() works)
const blue = document.querySelector('.blue');
// if you desire to use querySelectorAll you can have something similar to
// .each() like: [...document.querySelectorAll('.blue')].map(element => {});
// this is not a necessity but keeps code a little more organized,
// instead of throwing this into line 22.
const nodes = [];
let element = blue;
while(element = element.nextElementSibling) {
nodes.push(element);
}
// let's create a new div
const wrapper = document.createElement('div');
// and add the classname of your desire.
wrapper.classList.add('wrapper');
// now let's iterate over all nodes we stored earlier:
nodes.map(element => wrapper.appendChild(element));
// and append the wrapper to the .main div:
blue.parentNode.appendChild(wrapper);
// and for the fun of it, let's display the outcome:
document.body.appendChild(document.createElement('code')).textContent = blue.parentNode.outerHTML;
div {
padding: 2px;
border: 1px dotted #000;
min-height: 20px;
box-sizing: border-box;
position: relative;
}
<div id="main">
<div class="blue"></div>
<div class="green"></div>
<div class="yellow"></div>
</div>
i just realized you just want to iterate after the first child…
let's try this then:
// let's grab the main element:
const main = document.querySelector('#main');
// you could also do this: document.querySelector('.blue').parentNode;
// now let's grab the children of that node and strip the first one:
const nodes = [...main.children].splice(1);
// now let's create the wrapper div
const wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
// and append all children:
nodes.map(node => wrapper.appendChild(node));
// and ofc add the wrapper to the container:
main.appendChild(wrapper);
div {
padding: 2px;
border: 1px dotted #000;
min-height: 20px;
box-sizing: border-box;
position: relative;
}
<div id="main">
<div class="blue"></div>
<div class="green"></div>
<div class="yellow"></div>
</div>
Try below code.
var allBlues = document.querySelectorAll(".blue");
var divWrapper = document.createElement("div");
divWrapper.className = "wrapper";
for(var i = 0; i < allBlues.length; i++){
// Iterate through all the siblings.
var tempEle;
while(tempEle = allBlues[i].nextElementSibling){
divWrapper.appendChild(tempEle);
}
}
main.appendChild(divWrapper);
.blue{
}
<div id="main">
<div class="blue"></div>
<div class="green"></div>
<div class="yellow"></div>
</div>

What's the best way to add an element in an existing class element with basic j.s , jQuery?

Say I had some code in HTML like:
<div id="some_element" class="element_class">
How do I add/create a new div element and add it to the "element_class" with j.s/jQuery?
You can do like this using only javascript
var createDiv = document.createElement('div');
createDiv.textContent='inner div';
document.getElementById('some_element').appendChild(createDiv)
Using Jquery
To add elements at the end
$('#some_element').append("<div>1</div><div>2</div>");
To add element in in the starting
$('#some_element').prepend("<div>1</div><div>2</div>");
Here's a simple solution. Hope it helps!
$(document).ready(function(){
$("#mybutton").click(function () {
if($('.newDiv').length !== 1){
$("#some_element").append("<div class = 'newDiv'>This is a new div</div>");
}
});
});
.newDiv{
height: 80px;
width: 40px;
background: yellow;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button id = "mybutton">Click me</button>
<div id="some_element" class="element_class">

jQuery :has selector filter trouble

I have some containers with ids="container1", "container2", "container3"...
They can have one of two types of tags inside: tables or canvas.
I want to hide one of them depending on the device orientation.
I have tried with this
$('[id^=container]:has(canvas)').hide();
or
$('[id^=container]:has(table)').hide();
but both hide all the containers, don't filtering their inside tags.
You can do
var x = $('[id^=container]').find("table").length;
// Will be 0 if no table inside it
if(x==0) { .. }
else { .. }
You can use classes on your containers instead of ids. Here's a JSFiddle demo.
For better performance in modern browsers, use $( "your-pure-css-selector" ).has( selector/DOMElement ) instead.
Source: https://api.jquery.com/has-selector/
Basically I made a 3 containers. One with a table, one with a canvas and one with nothing.
<div class="container green">
<table></table>
</div>
<div class="container blue">
<canvas></canvas>
</div>
<div class="container red"></div>
And a quick CSS to have the divs visible.
div.container{
display: inline-block;
height: 50px;
margin: 10px;
width: 50px;
}
div.green{
background-color: green;
}
div.blue{
background-color: blue;
}
div.red{
background-color: red;
}
And to complete it, a jQuery that executes when the document is ready.
$(document).ready(function(){
$('div.container').has('canvas').hide();
});
If you know the element by which you want to grab the container is not nested within additional tags, you can use the parentNode property of an HTML element to climb up the DOM tree and hide the parent.
document.querySelector("[id^=container] > table").parentNode.style.display= "none";
Example that demos the concept:
document.getElementById("input").addEventListener("change", function() {
document.getElementById("container1").style.display = "block";
document.getElementById("container2").style.display = "block";
document.querySelector("[id^=container] > " + this.value).parentNode.style.display = "none";
});
#container1 {
border: 1px solid red;
}
#container2 {
border: 1px solid blue;
}
<select id="input">
<options>
<option value="table">Hide the table</option>
<option value="canvas">Hide the canvas</option>
</options>
</select>
<div id="container1">Table
<table></table>
</div>
<div id="container2">Canvas
<canvas></canvas>
</div>
I didn't realized I had a global container with id= "container*".
What a silly mistake. Sorry for stealing your time, and thank you everyone!

Categories