Append HTMLElement to the middle of an inline element - javascript

FYI: It is desirable that solutions be strictly vanilla Javascript.
How can I append an HTMLElement object to the middle of an element?
Here's a sample with a bit of what I mean.
const paragraph = document.createElement('p')
paragraph.innerHTML = 'Here is some text.<br><br>There is some text.'
document.body.appendChild(paragraph)
const wrappper = document.createElement('div')
const button = document.createElement('button')
button.onmouseup = () =>
{
// Do something
}
wrapper.appendChild(button)
Now imagine for a moment that I want to put the wrapper element inside of the paragraph element. But, not at the beginning or the end of it, but rather somewhere in the middle such as between the <br> tags. (But not necessarily after a tag) This can be done rather easily by taking the outerHTML of wrapper and inserting it into the paragraph's innerHTML via substrings, but this presents a problem. The resulting elements now in the flow of the html page are not the same as wrapper or button, which is evident when logging them, or when there is no onmouseup event being triggered.
So, ultimately, how do I put the exact HTMLElements referenced by the defined variables into the flow of the document in the middle of the contents of another element?

Find the <br> element and use insertAdjacentElement to insert after it.
const paragraph = document.createElement('p')
paragraph.innerHTML = 'Here is some text.<br><br>There is some text.'
document.body.appendChild(paragraph)
const wrappper = document.createElement('div')
const button = document.createElement('button')
button.innerText = 'Click';
const br = paragraph.querySelector("br");
br.insertAdjacentElement('afterend', button);

Maybe have a temporary <span> with a known id and then replace it with the element you wish to replaceWith would do...
const paragraph = document.createElement('p')
paragraph.innerHTML = 'Here is some text.<br><span id="destination"></span><br>There is some text.'
document.body.appendChild(paragraph)
const wrapper = document.createElement('div')
const button = document.createElement('button')
button.innerText = "here"
button.onmouseup = () =>
{
// Do something
}
wrapper.appendChild(button)
let destination = document.querySelector("#destination")
destination.replaceWith(wrapper)

Related

How to post a paragraph in HTML with CSS styling applied?

I am using the following code to print a paragraph when the button is clicked:
document.querySelector('button')
.addEventListener('click', function() {
const p = document.createElement('p');
p.id = "text";
const val = document.getElementById('forminput').value;
if (val.length) {
p.innerHTML = val;
document.querySelector('div').appendChild(p);
}
});
When the paragraph is posted, I want it to retain the same CSS styling as well as the same onclick function as the styling and function I use for other content.
What would be the right way to do it?
If you have some styling set up for your p tags already, then this would automatically apply when you render the new p tag.
Else you can create a custom css class that holds the styling you're wanting to apply, and then add this classList to your newly rendered p tag as follows:
const p = document.createElement('p');
p.classList.add('your-class');

How to write less code using JavaScript DOM Elements?

Intro: I am using fetch method to get data from API. inside forloop i am not using the template string because somebody told me. it is not a good way to write HTML code inside template sting. So that's why i am using javascript DOM Element to render out the data from API. But i am new in JavaScript i want to know how can i write less code with DOM Element. the code below is too much and complicated. I have dropdown menu inside pending-sale div which contain a form attributes. Which I haven't written yet, if i write that dropdown menu code my code will be even more complicated as I write the code..
Needs: i just want to know how can i write my code less and understandable? Can anyone tell me if the code I am writing is correct? If this is not true, please guide me a little...
I would be grateful for any help.
main.js
const orderCard = document.querySelector('#pending-sales');
function pendingSaleBuild() {
orderCard.innerHTML = ''
fetch('/pending-sale-api/')
.then((res) => res.json())
.then((data) => {
data.map(item => {
// card title
const colLg = document.createElement('div')
colLg.classList.add('col-lg-12')
const hPanel = document.createElement('div')
hPanel.classList.add('hpanel')
hPanel.classList.add('hyellow')
const pBody = document.createElement('div')
pBody.classList.add('panel-body')
hPanel.appendChild(pBody)
colLg.appendChild(hPanel)
orderCard.appendChild(colLg)
const h5 = document.createElement('h5');
h5.classList.add('text-capitalize')
// card tilte link
const a = document.createElement('a');
h5.appendChild(a)
linkText = document.createTextNode(item.customers);
a.appendChild(linkText);
a.href = "#";
pBody.appendChild(h5);
// hr Element
const hr = document.createElement('hr');
pBody.appendChild(hr)
// row div
const rowDiv = document.createElement('div');
rowDiv.classList.add('row');
// project - label div
const colDiv = document.createElement('div');
colDiv.classList.add('col-sm-4');
rowDiv.appendChild(colDiv);
// project lable div
const proLable = document.createElement('div');
proLable.classList.add('project-label');
proLable.innerText = 'Saler Name';
colDiv.appendChild(proLable);
// small text Element
const smallEle1 = document.createElement('small')
smallEle1.innerText = item.saler
colDiv.appendChild(smallEle1);
const colDiv2 = document.createElement('div');
colDiv2.classList.add('col-sm-4');
rowDiv.appendChild(colDiv2);
// project lable div
const proLable2 = document.createElement('div');
proLable2.classList.add('project-label');
proLable2.innerText = 'Timestamp';
colDiv2.appendChild(proLable2);
// small text Element
const smallEle2 = document.createElement('small')
smallEle2.innerText = 'item.created_on'
colDiv2.appendChild(smallEle2);
const colDiv3 = document.createElement('div');
colDiv3.classList.add('col-sm-4');
rowDiv.appendChild(colDiv3);
// project lable div
const proLable3 = document.createElement('div');
proLable3.classList.add('project-label');
proLable3.innerText = 'Total Price';
colDiv3.appendChild(proLable3);
// small text Element
const smallEle3 = document.createElement('small')
smallEle3.innerText = '$ 124547'
colDiv3.appendChild(smallEle3);
pBody.appendChild(rowDiv);
})
});
};

How can I write down paragraphs in HTML with Javascript without the use of getElementbyId?

So, i was working on this little formatting experiment with HTML, where you could create a paragraph via input and it would create an HTML paragraph on the screen. I did it by doing this.
HTML:
<button onclick="create_para()">Create Paragraph</button>
<p id="p1"></p>
Javascript:
function create_para(){
var p = window.prompt("Enter paragraph text: ");
document.getElementById("p1").innerHTML = p;
}
And, it worked! The only problem is that I wanted it so you could click the button again and again and it would create new paragraphs without replacing the old one. The only way I thought I could do it would be by making a bunch of tags with different classes, and having a bunch of functions, and a lot of buttons, but that's inefficient and too complicated.
So, I found out about document.write() and document.writeln(). So I used it in my code, but turns out it just deletes all other HTML code and just leaves it with the lines I wrote.
Therefore, is the a form of writing down paragraph lines without the use of ID's, or a form where it wouldn't delete all HTML code?
Thanks.
You can do something like:
function create_para(){
var p = window.prompt("Enter paragraph text: ");
var elem = document.createElement('p');
elem.innerText = p;
document.body.appendChild(elem)
}
EDIT: to add an id to each, you can add a global counter variable.
var i = 0;
function create_para(){
var p = window.prompt("Enter paragraph text: ");
var elem = document.createElement('p');
elem.innerText = p;
elem.id = '' + i;
i++;
document.body.appendChild(elem);
}
You can create a div container and then creates HTML Elements dinamically with your function, also you can assing an id to your new element, try this:
let div = document.getElementById('container');
function create_para(){
let p = document.createElement('p');
let txt = window.prompt("Enter paragraph text: ");
p.textContent = txt;
p.id = 'your id';
div.appendChild(p);
}
<div id='container'></div>

JavaScript create span element inside div

The following is the HTML that does what I want. It displays category: and beneath a value that I send in JavaScript.
<div id="category-order-id" class="additional-order-info">
<!-- <span class="additional-order-info-grey">category:</span>
Clothes -->
</div>
And here is my JavaScript
let orderCategory = document.getElementById("category-order-id");
orderCategory.textContent = `${order.category}`;
let categorySpan = document.createElement("span");
categorySpan.setAttribute("class", "additional-order-info-grey");
categorySpan.textContent = "category:";
orderCategory.appendChild(categorySpan);
What this code does, it that it first displays Clothes value that I send with JavaScript and beneath it display category.
Why I am creating a span element here is because if I set textContent of orderCategory it wil not display the span at all.
What am I doing wrong here?
textContent property replaces all the content in the element. If you want to keep order.category and "category:" as content, you need to use the appendChild function:
let orderCategory = document.getElementById("category-order-id");
const catTextContent = document.createElement("span");
catTextContent.textContent = order.category;
let categorySpan = document.createElement("span");
categorySpan.setAttribute("class", "additional-order-info-grey");
categorySpan.textContent = "category:";
orderCategory.appendChild(catTextContent);
orderCategory.appendChild(categorySpan);

Without jQuery, create a new element AFTER a specifc element and then "MOVE" some other elements on the page into it with JAVASCRIPT only

I have the following jQuery code to inject an element after another element and then MOVE some elements into it. I wasn't able to find any clear vanilla js functions do this as most people were suggesting insertBefore or insertAdjacentElement but none of them work in the chrome console. I'm trying to just do this in vanilla js.
jQuery('<div id="jsinjected"><i class="field-name-title"></i></div>').insertAfter('.field-name-body');
jQuery('.group-header .field-name-title ~ .field').appendTo('#jsinjected');
Will this work?
const after = document.getElementById("element");
const move = document.getElementById("move");
const parent = after.parentNode;
const tmp = document.createElement("div");
tmp.innerHTML =
`<div id="jsinjected"><i class="field-name-title">injected</i></div>`;
const newElement = tmp.firstElementChild;
var next = after.nextSibling;
if(next === null){
next = document.createTextNode(" ");
parent.appendChild(next);
}
parent.insertBefore(newElement, next);
newElement.appendChild(move);
<div><div id="move">move this</div>
<div id="element">after</div></div>

Categories