In Javascript, I am trying to dynamically create an HTML <template> element, append an <h1> element as its child, clone the template's contents, and then append the template to the document body.
The problem is when I access the content property of the template it just returns #document-fragment.
Here's the code:
var temp = document.createElement('template');
var h1 = document.createElement('h1');
h1.textContent = 'hello';
var div = document.createElement('div').appendChild(h1)
temp.appendChild(div)
console.log('temp: ', temp)
console.log('temp content: ', temp.content)
var c = document.importNode(temp.content, true)
document.body.appendChild(c)
And here is the output for the console.log's:
What am I doing wrong here? Why is the template's contents showing up as empty?
When you create a <template>, you should append DOM content (with appendChild()) to the .content property (which is a DocumentFragment), not to the element itself.
var temp = document.createElement('template');
var h1 = document.createElement('h1');
h1.textContent = 'hello';
var div = document.createElement('div')
div.appendChild(h1)
//append DOM to .content
temp.content.appendChild(div)
console.log('temp: ', temp)
console.log('temp content: ', temp.content)
var c = document.importNode(temp.content, true)
document.body.appendChild(c)
An alternative is to add a HTML string via the innerHTML property.
temp.innerHTML = '<div><h1>Hello</h1></div>'
Note, var div = document.createElement('div').appendChild(h1) sets div variable to h1, the appended element, not div element; see What is the behavior of document.createElement when passed as an argument?.
Set .innerHTML of <template> to .outerHTML of div element, call .appendChild() chained to document.body with temp.content as parameter.
window.onload = function() {
var temp = document.createElement('template');
var h1 = document.createElement('h1');
h1.textContent = 'hello';
var div = document.createElement('div');
div.appendChild(h1);
temp.innerHTML = div.outerHTML;
console.log('temp: ', temp.content);
document.body.appendChild(temp.content);
}
<body></body>
Related
So I have this html code i'm trying to replicate using dom manipulation
<h1 id="intro-text">
HAMADILYTICAL<span id="word">Grill</span>
</h1>
I have some styling for that specific span so that it doesn't render in the same line.
This is what I tried but it's obviously not going to work because I'm appending the child after that node not inside of it.
// main content
const mainContent = document.createElement('div');
const introText = document.createElement('h1');
const span = document.createElement('span');
mainContent.className = 'main-content';
introText.id = 'intro-text';
span.id = 'word';
introText.textContent = `HAMADILYTICAL Grill`;
content.appendChild(mainContent);
mainContent.appendChild(introText);
introText.appendChild(span);
using innerHTML fixed it
const mainContent = document.createElement('div');
const introText = document.createElement('h1');
mainContent.className = 'main-content';
introText.id = 'intro-text';
introText.innerHTML = `<h1 id="intro-text">
HAMADILYTICAL <span id="word">Grill</span></h1>`;
content.appendChild(mainContent);
mainContent.appendChild(introText);
I have an element in js and I want to add text using innertext and add it to a div with an id how would I do this?
html
<div id="divone">
</div>
js
var h1 = document.createElement('h1');
var h1 = document.createElement('h1');
h1.innerText = "ABC";
document.getElementById('divone').appendChild(h1);
<div id="divone"></div>
Just create h1
appendChild to div.
var h1 = document.createElement('h1');
h1.innerText = "ABC";
document.getElementById('divone').appendChild(h1);
You can achieve by using the append child function
var example = document.getElementById('divone');
var h1 = document.createElement('h1');
h1.innerText = "hi";
example.appendChild(h1);
Here's an example
What would be the shortest way to do the following :
var div = document.createElement('div');
div.className = 'divClass';
div.innerHTML = 'Div Content';
... without any external libraries
class Div {
constructor(className, innerHTML) {
let div = document.createElement("div");
div.className = className;
div.innerHTML = innerHTML;
return div;
}
}
let innerHTML = "LOL"
new Div(divClass, innerHTML);
This would be the shortest way to doing it again and again while still having some order inside your code, IMO.
Write a function to do it in one line:
function tag(tagNameAndClass, innerHTML) {
var parts = (tagNameAndClass || 'div').split(/\./g);
var elem = document.createElement(parts.shift());
elem.className = parts.join(' ');
if (innerHTML) elem.innerHTML = innerHTML;
return elem;
}
Examples of uses:
tag('div.divClass', 'Div Content') // <div class="divClass">Div Content</div>
tag('.class-one.class-two', 'Content') // <div class="class-one class-two">Content</div>
tag('h1.super', 'My Super Heading') // <h1 class="super">My Super Heading</h1>
What would be the shortest way to do the following [...]
We can imagine a situation in which the div already exists in the DOM while the CSS style rule display:none ensures it remains absent from the visible document flow.
The following single line in javascript will make the element reappear into the visible document flow:
document.getElementsByClassName('divClass')[0].style.display = 'block';
Probably the best solution I have came up with so far :
var el = function(type,props,appends){
var el = document.createElement(type);
if(props) for(var x in props) el[x] = props[x];
if(appends) for(var x in appends) el.appendChild(appends[x]);
return el;
}
and then when using it (creating a popup with header and body example) :
$title = el('div',{className:'title',innerHTML:'Item Title'});
$remove = el('div',{className:'remove',innerHTML:'X'});
$header = el('div',{className:'header'},[$title,$remove,el('div',{className:'clear'})]);
$body = el('div',{className:'body',innerHTML:'body'});
$el = el('div',{className:'item'},[$header,$body]);
Consider this my value:
var value = "<br><br><div class="test">-- Thanks, <br><div><br></div></div>";
I want to remove test class div tag i.e <div class="test1"> and related to closing tag </div>.
Expecting results will be:
"<br><br>-- Thanks, <br><div><br></div>"
I am trying with regular expression:
value = value.replace(/(<div class="test">|<\/div>)/g, '');
but it's removing adjacent div tag:
<br><br><div class="test">-- Thanks, <br><div><br>
not the exactly with the closing tag.
How to do this?
Your best bet here is to use the HTML parser built into the browser. For instance:
var div, divToRemove, node, sibling;
div = document.createElement('div');
div.innerHTML = value;
divToRemove = div.querySelector('.test');
for (node = divToRemove.firstChild, sibling = node.nextSibling;
node;
node = sibling, sibling = node && node.nextSibling) {
divToRemove.parentNode.insertBefore(node, divToRemove);
}
divToRemove.parentNode.removeChild(divToRemove);
value = div.innerHTML;
Live Example:
var value = '<br><br><div class="test">-- Thanks, <br><div><br></div></div>';
snippet.log("Before: " + value);
var div, divToRemove, node, sibling;
div = document.createElement('div');
div.innerHTML = value;
divToRemove = div.querySelector('.test');
for (node = divToRemove.firstChild, sibling = node.nextSibling; node; node = sibling, sibling = node && node.nextSibling) {
divToRemove.parentNode.insertBefore(node, divToRemove);
}
divToRemove.parentNode.removeChild(divToRemove);
value = div.innerHTML;
snippet.log("After: " + value);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You need to first save parent div's html in a variable
var html = document.getElementByClassName('test1').innerHtml;
Then remove the div:
document.getElementByClassName('test1').remove();
Then append the html to the parent of the div
var bodyHtml = document.getElementByTagName('body');
bodyHtml = bodyHtml + html;
Use the DOM to get it right
var html = '<br><br><div class="test">-- Thanks, <br><div><br></div></div>';
var frag = document.createElement('div');
frag.innerHTML = html;
var tgt = frag.querySelector('.test');
var par = tgt.parentNode;
while(tgt.firstChild) {
par.insertBefore(tgt.firstChild, tgt);
};
tgt.remove();
console.log(frag.innerHTML);
I need to wrap up the body content inside a div dynamically. I tried the below code and i am getting, 'newDiv.append function is undefined'. I tried with setTimeout as well and checked after the jquery file loads made for loop to get loaded. Still getting the same error.
function initiate() {
var jq_script = document.createElement('script');
jq_script.setAttribute('src', '//code.jquery.com/jquery-1.11.2.min.js');
document.head.appendChild(jq_script);
var newDiv = document.createElement('div')
newDiv.setAttribute('id', 'wrapper');
var bodyChildren = document.body.childNodes;
for (var i = 0; i < bodyChildren.length; i++) {
newDiv.append(bodyChildren[i]);
}
document.body.appendChild(newDiv);
}
initiate();
And i tried this as well to wrap up the body's innerHTML with a div element.
function initiate() {
var jq_script = document.createElement('script');
jq_script.setAttribute('src', '//code.jquery.com/jquery-1.11.2.min.js');
document.head.appendChild(jq_script);
var div = document.createElement("div");
div.id = "wrapper";
while (document.body.firstChild) {
div.appendChild(document.body.firstChild);
}
document.body.appendChild(div);
}
initiate();
This keeps on adding the wrapper element inside body. And the above script is inside iframe.
Any solution on this?
Two problems:
It's appendChild, not append.
Once that's out of the way, though, the other problem is in your loop: childNodes is a dynamic list, and so when you move a child out of body into newDiv, the list changes, making your indexes invalid.
You can fix that by just looping, moving first child into your div, until the body runs out of children, then append the div:
var newDiv = document.createElement('div')
newDiv.id = "wrapper"; // You don't need or want setAttribute here
var bodyChildren = document.body.childNodes;
while (bodyChildren.length) {
newDiv.appendChild(bodyChildren[0]);
}
document.body.appendChild(newDiv);
Or actually, you don't even need the list, you can use firstChild:
var newDiv = document.createElement('div')
newDiv.id = "wrapper"; // You don't need or want setAttribute here
while (document.body.firstChild) {
newDiv.appendChild(document.body.firstChild);
}
document.body.appendChild(newDiv);