Creating multiple elements with javascript - javascript

I have an html element tree sample(below) that I want to return with relevant data for every match I got in database.Lets say there are 5 matches.
Do I need to create 5 given elements and populate them with javascript data?
I'm gonna run a loop, but this looks like it will be performance costly(creating all element tree for every match). Instead, can i use the given element(pic) populate it with javascript and drop it onto dom instead (x times)? If possible how ?
<!-- sample elem -->
<div class="col-12 col-md-4" style="display: none">
<div class="card my-3 mx-1">
<img src="" alt="img">
<div class="card-body">
<div class="row">
<div class="col-12 p-1">Country</div>
<div class="col-3 p-1">State</div>
<div class="col-4 p-1">City</div>
</div>
</div>
</div>
</div>

To further elabourate on my comment: it is often the repeated insertion of elements into the DOM tree that causes performance issue, because the document needs to reflow every time a new node is inserted. You should not be worried about calling/invoking document.createElement() too many times: that is the least of your concern.
Therefore, I would suggest that you use a function to create your entire sample element. You can then invoke this function to create the entire card element as you please in each iteration of the loop, and then append it to the document fragment.
Pseudo code:
function createCard() {
// Create the entire `sample element` as you would call it
const el = <something>;
return el;
}
// Create new document fragment to hold all the nodes
// At this point, we are NOT injecting them into the DOM yet
const fragment = new DocumentFragment();
// Go through your data and create new card for each data point
for (let i = 0; i < 5; i++) {
fragment.appendChild(createCard());
}
// Now this is when you insert the entire bulk of the content into the DOM
document.querySelector('#myInsertionTarget').appendChild(fragment);
A proof-of-concept code is as follow:
// Since we are creating so many `<div>` elements
// It helps to further abstract its logic into another function
function createDivElement(classes, text) {
const div = document.createElement('div');
if (classes.length)
div.classList.add(...classes);
if (text)
div.innerText = text;
return div;
}
// Call this whenever you want to create a new card
function createCard(i) {
const colCountry = createDivElement(['col-12', 'p-1'], 'Country');
const colState = createDivElement(['col-3', 'p-1'], 'State');
const colCity = createDivElement(['col-4', 'p-1'], 'City');
const row = createDivElement(['row']);
row.appendChild(colCountry);
row.appendChild(colState);
row.appendChild(colCity);
const cardBody = createDivElement(['card-body']);
cardBody.appendChild(row);
const image = document.createElement('img');
image.alt = 'img';
// Proof-of-concept image source, you can ignore this!
image.src = `https://placehold.it/100x50?text=Image%20${i+1}`;
const imageLink = document.createElement('a');
imageLink.href = '#';
imageLink.appendChild(image);
const card = createDivElement(['card', 'my-3', 'mx-1']);
card.appendChild(imageLink);
card.appendChild(cardBody);
const outer = createDivElement(['col-12', 'col-md-4']);
// outer.style.display = 'none';
outer.appendChild(card);
return outer;
}
// Create new document fragment
const fragment = new DocumentFragment();
// In each iteration of the loop, insert the new card element into fragment
for (let i = 0; i < 5; i++) {
const el = createCard(i);
fragment.appendChild(el);
}
// When you're done generating the entire set of elements
// You can then insert the fragment into your DOM (finally!)
document.querySelector('#app').appendChild(fragment);
<div id="app"></div>

Performance impact is not great for 15-20 elements and that markup alone.
However if you can prove it's slow, know that strings are faster. So a faster approach is this:
Store the markup template as a string
Create a string with the final markup - it can repeat the template as many times as it needs, obviously filled with that
Insert markup in target node
Here is how that would look like:
const products = [{ title: 'gearbox' }, { title: 'drive shaft' }, { title: 'spark plug'}]
const myTemplate = '<div class="product">{title}</div>'
const finalMarkup = products.map(({ title }) => myTemplate.replace('{title}', title))
document.getElementId('targetNode').innerHtml = finalMarkup

Related

How to add an instantiated objects to the DOM? Simulating React in Vanilla JS

I am trying to complete an optional project for my class, we have been using React for the past month or so and I have become pretty comfortable with the framework. Though, in order to actually have a better understanding of how things are actually working under the hood, I am trying to recreate the process of instantiating objects and rendering them on the page with vanilla JavaScript.
I'm posting now because I've hit a wall and I'm having difficulty finding helpful material online.
In the following code I have successfully querySelected my inputs and a button, I want to render an object onto the page that displays unique instance of the Idea class. The object comes with some buttons: favorite, delete, upvote, and downvote.
What I've managed to accomplish so far:
target the DOM elements and capture their inputs
instantiate an object with the input values and push it into an array
What I am attempting to do:
render each object element in the ideas array to the DOM
Be able to click the buttons on the rendered output and change the state of that respective object + remove the correct object on click.
The current logic I've written so far:
//buttons
const saveButton = document.querySelector(".save-button");
//inputs
const titleInput = document.querySelector("[name='title']");
const bodyInput = document.querySelector("[name='body']");
//output
const outputSection = document.querySelector(".main-outputs");
let titleValue = "";
let bodyValue = "";
const ideas = [];
titleInput.addEventListener("keyup", e => {
titleValue = "";
titleValue += e.target.value;
});
bodyInput.addEventListener("keyup", e => {
bodyValue = "";
bodyValue += e.target.value;
});
saveButton.addEventListener("click", e => {
e.preventDefault();
const ideaObject = new Idea(titleValue, bodyValue);
ideas.push(ideaObject);
console.log("ideas: ", ideas);
render(ideaObject, outputSection);
});
const render = function(template, node) {
if (!node) return;
node.innerHTML += template;
};
class Idea {
constructor(title, body) {
this.title = title;
this.body = body;
this.favorite = false;
this.quality = "swill";
this.id = Date.now();
this.content = this.content;
}
renderIdea() {}
}
The html each element 'should' render on the page.
<article class="main-output-card">
<header>
<img src="./icons/star.svg" alt="" />
<img src="./icons/delete.svg" alt="" />
</header>
<section>
<h3 class="idea-title">Idea Title</h3>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque
consectetur voluptas fuga accusantium!
</p>
</section>
<footer>
<img src="./icons/upvote.svg" alt="" />
<h5 class="idea-quality">Quality: <span>Swill</span></h5>
<img src="./icons/downvote.svg" alt="" />
</footer>
</article>
Any help would be appreciated, it seems like a good challenge but I feel like I'm in over my head.
Would love to see what I should do / what I am doing wrong.
Thank you!
The code has a lot of gaps. Here are some thoughts:
You seem to be intending to inject some values in a html template which is in the browser, by changing the inner html of it. This will mean that you will only be able to add one element to your page, as you are not creating new elements.You will need to create more DOM elements if you want to have multiple 'Ideas' being displayed.
Generating new DOM elements can be achieved by cloning the node you want to use. Or you might make a constructor for the DOM elements using the create method.
Once you have you DOM element you can insert into the page by using one of the various insertion methods.
A way to make changes to each of the element would be to simply give each an id, and selecting each of them by id and performing the desired changes to them.
To delete the correct element after a certain click event, you can use the properties on the event object, in particular event.target, to find which element was clicked.
The heuristics of syncing the state and the DOM I'll leave it up to you.
So, if you are wanting to render the entire thing from scratch (I assume you are), then you could do this. It is all vanilla JavaScript, no JQuery or anything like that.
There is 1 VERY important thing to remember though. Just like with React, Vue, etc., if the user has JavaScript disabled in their browser, they will see nothing when they open the page.
/* your other existing functions */
const createImg = function(src, alt) {
let img = document.createElement('img');
img.setAttribute('src', src);
img.setAttribute('alt', alt);
return img;
}
const createTextElement = function (type, text, className) {
let el = document.createElement(type);
el.innerText = text;
if (className) el.className = className;
}
class Idea {
constructor(title, body) {
this.title = title;
this.body = body;
this.favorite = false;
this.quality = "swill";
this.id = Date.now();
this.content = this.content;
}
renderIdea() {
// Create the main container
let article = document.createElement('article');
article.className = 'main-output-card';
// Create the header container and add the icons to it
let articleHeader = document.createElement('header');
articleHeader.appendChild(createImg('./icons/star.svg', ''));
articleHeader.appendChild(createImg('./icons/delete.svg', ''));
// Create the content section and add the content to it
let articleSection = document.createElement('section');
articleSection.appendChild(createTextElement('h3', this.title, 'idea-title'));
articleSection.appendChild(createTextElement('p', this.body));
// Create the article footer and add content to it
articleFooter = document.createElement('footer');
let articleFooterQuality = document.createElement('h5');
articleFooterQuality.className = 'idea-quality';
articleFooterQuality.innerHtml = `Quality: <span>${this.quality}</span>`;
articleFooter.appendChild(createImg('./icons/upvote.svg', ''));
articleFooter.appendChild(articleFooterQuality);
articleFooter.appendChild(createImg('./icons/downvote.svg', ''));
}
}

Javascript Typewriter Effect from element childNodes

I am trying to create a type writer effect that will get the nodes of an element and then display the values of those nodes sequentially at a given speed. If the node is a text node I want it to go in and sequentially display each character in that text.
HTML:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!-- item will be appened to this layout -->
<div id="log" class="sl__chat__layout">
</div>
<!-- chat item -->
<script type="text/template" id="chatlist_item">
<div data-from="{from}" data-id="{messageId}" id="messageID">
<div id="messageBox">
<span id="message">
{message}
</span>
</div>
</div>
</script>
Javascript:
// Please use event listeners to run functions.
document.addEventListener('onLoad', function(obj) {
// obj will be empty for chat widget
// this will fire only once when the widget loads
});
document.addEventListener('onEventReceived', function(obj) {
// obj will contain information about the event
e++
typeEffect(e);
});
var speed = 50;
var e = 1;
function typeEffect(inp) {
var o = inp;
document.getElementById("messageID").id= "messageID"+o;
document.getElementById("message").id= "message"+o;
var text = $("#message"+o).text();
$("#message"+o).text('');
var i = 0;
var timer = setInterval(function() {
if(i < text.length) {
$("#message"+o).append(text.charAt(i));
i++;
}
else{
clearInterval(timer);
};
}, speed);
}
Here is an example of an element with the id "message2". As you can see it contains some text, then a span containing an image and then some more text.
<span id="message2">
Hello
<span class="emote">
<img src="https://static-cdn.jtvnw.net/emoticons/v1/1251411/1.0">
</span>
There
</span>
In my code posted above I am able to create the typewriter effect of the text. However, using the above example, I can't figure out a way to type "Hello" then the span with the image and then "There".
I have tried to get the nodes like this:
var contents = document.getElementById("message"+o).childNodes;
When I log that to the console I get: NodeList(3) [text, span.emote, text]
From there however I am having trouble accessing the nodeValues. I keep getting errors thrown. I am not sure exactly what I am doing wrong. From there I am also not sure the proper way to empty the "message"+o element and then refill it with the information.
Hopefully that explains everything!
By using $.text(), you are getting your Element's textContent, and all its markup content is gone (actually all its children).
In order to retain this content, you need to store the DOM nodes instead of just their textContent.
From there, you will have to detach the DOM tree and walk it while appending every Element, iterating slowly over each TextNode's textContent.
However, doing so is not that easy. Indeed, the fact that we will re-append the DOM nodes inside the document means that the detached DOM tree
we were walking will get broken.
To circumvent that, we thus need to create a copy of the detached DOM tree, that we will keep intact, so we can continue walking it just like if it were the original one.
And in order to know where to place our elements, we need to store each original node as a property of the cloned one.
To do so, we'll create two TreeWalkers, one for the original nodes, and one for the cloned version. By walking both at the same time, we can set our clones' .original property easily.
We then just have to go back to the root of our clones TreeWalker and start again walking it, this time being able to append the correct node to its original parentNode.
async function typeWrite(root, freq) {
// grab our element's content
const content = [...root.childNodes];
// move it to a documentFragment
const originals = document.createDocumentFragment();
originals.append.apply(originals, content);
// clone this documentFragment so can keep a clean version of the DOM tree
const clones = originals.cloneNode(true);
// every clone will have an `original` node
// clones documentFragment's one is the root Element, still in doc
clones.original = root;
// make two TreeWalkers
const originals_walker = document.createTreeWalker(originals, NodeFilter.SHOW_ALL, null);
const clones_walker = document.createTreeWalker(clones, NodeFilter.SHOW_ALL, null);
while(originals_walker.nextNode() && clones_walker.nextNode()) {
// link each original node to its clone
clones_walker.currentNode.original =
originals_walker.currentNode
}
while(clones_walker.parentNode()) {
// go back to root
}
// walk down only our clones (will stay untouched now)
while(clones_walker.nextNode()) {
const clone = clones_walker.currentNode;
const original = clone.original;
// retrieve the original parentNode (which is already in doc)
clone.parentNode.original
.append(original); // and append the original version of our currentNode
if(clone.nodeType === 3) { // TextNode
const originalText = original.textContent;
// we use a trimmed version to avoid all non visible characters
const txt = originalText.trim().replace(/\n/g, '');
original.textContent = ''; // in doc => empty for now
let i = 0;
while(i < txt.length) {
await wait(freq); // TypeWriting effect...
original.textContent += txt[i++];
}
// restore original textContent (invisible to user)
original.textContent = originalText;
}
}
}
typeWrite(message2, 200)
.catch(console.error);
function wait(time) {
return new Promise(res => setTimeout(res, time));
}
<span id="message2">
Hello
<span class="emote">
<img src="https://static-cdn.jtvnw.net/emoticons/v1/1251411/1.0">
</span>
There
</span>

JS - Wrap all child elements of div in a wrapper div [duplicate]

I want to wrap all the nodes within the #slidesContainer div with JavaScript. I know it is easily done in jQuery, but I am interested in knowing how to do it with pure JS.
Here is the code:
<div id="slidesContainer">
<div class="slide">slide 1</div>
<div class="slide">slide 2</div>
<div class="slide">slide 3</div>
<div class="slide">slide 4</div>
</div>
I want to wrap the divs with a class of "slide" collectively within another div with id="slideInner".
If your "slide"s are always in slidesContainer you could do this
org_html = document.getElementById("slidesContainer").innerHTML;
new_html = "<div id='slidesInner'>" + org_html + "</div>";
document.getElementById("slidesContainer").innerHTML = new_html;
Like BosWorth99, I also like to manipulate the dom elements directly, this helps maintain all of the node's attributes. However, I wanted to maintain the position of the element in the dom and not just append the end incase there were siblings. Here is what I did.
var wrap = function (toWrap, wrapper) {
wrapper = wrapper || document.createElement('div');
toWrap.parentNode.appendChild(wrapper);
return wrapper.appendChild(toWrap);
};
How to "wrap content" and "preserve bound events"?
// element that will be wrapped
var el = document.querySelector('div.wrap_me');
// create wrapper container
var wrapper = document.createElement('div');
// insert wrapper before el in the DOM tree
el.parentNode.insertBefore(wrapper, el);
// move el into wrapper
wrapper.appendChild(el);
or
function wrap(el, wrapper) {
el.parentNode.insertBefore(wrapper, el);
wrapper.appendChild(el);
}
// example: wrapping an anchor with class "wrap_me" into a new div element
wrap(document.querySelector('div.wrap_me'), document.createElement('div'));
ref
https://plainjs.com/javascript/manipulation/wrap-an-html-structure-around-an-element-28
If you patch up document.getElementsByClassName for IE, you can do something like:
var addedToDocument = false;
var wrapper = document.createElement("div");
wrapper.id = "slideInner";
var nodesToWrap = document.getElementsByClassName("slide");
for (var index = 0; index < nodesToWrap.length; index++) {
var node = nodesToWrap[index];
if (! addedToDocument) {
node.parentNode.insertBefore(wrapper, node);
addedToDocument = true;
}
node.parentNode.removeChild(node);
wrapper.appendChild(node);
}
Example: http://jsfiddle.net/GkEVm/2/
A general good tip for trying to do something you'd normally do with jQuery, without jQuery, is to look at the jQuery source. What do they do? Well, they grab all the children, append them to a a new node, then append that node inside the parent.
Here's a simple little method to do precisely that:
const wrapAll = (target, wrapper = document.createElement('div')) => {
;[ ...target.childNodes ].forEach(child => wrapper.appendChild(child))
target.appendChild(wrapper)
return wrapper
}
And here's how you use it:
// wraps everything in a div named 'wrapper'
const wrapper = wrapAll(document.body)
// wraps all the children of #some-list in a new ul tag
const newList = wrapAll(document.getElementById('some-list'), document.createElement('ul'))
I like to manipulate dom elements directly - createElement, appendChild, removeChild etc. as opposed to the injection of strings as element.innerHTML. That strategy does work, but I think the native browser methods are more direct. Additionally, they returns a new node's value, saving you from another unnecessary getElementById call.
This is really simple, and would need to be attached to some type of event to make any use of.
wrap();
function wrap() {
var newDiv = document.createElement('div');
newDiv.setAttribute("id", "slideInner");
document.getElementById('wrapper').appendChild(newDiv);
newDiv.appendChild(document.getElementById('slides'));
}
jsFiddle
Maybe that helps your understanding of this issue with vanilla js.
To simply wrap a div without the need of the parent:
<div id="original">ORIGINAL</div>
<script>
document.getElementById('original').outerHTML
=
'<div id="wrap">'+
document.getElementById('original').outerHTML
+'</div>'
</script>
Working Example: https://jsfiddle.net/0v5eLo29/
More Practical Way:
const origEle = document.getElementById('original');
origEle.outerHTML = '<div id="wrap">' + origEle.outerHTML + '</div>';
Or by using only nodes:
let original = document.getElementById('original');
let wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
wrapper.append(original.cloneNode(true));
original.replaceWith(wrapper);
Working Example: https://jsfiddle.net/wfhqak2t/
A simple way to do this would be:
let el = document.getElementById('slidesContainer');
el.innerHTML = `<div id='slideInner'>${el.innerHTML}</div>`;
Note - below answers the title of the question but is not specific to the OP's requirements (which are over a decade old)
Using the range API is making wrapping easy, by creating a Range which selects only the node wished to be wrapped, and then use the surroundContents API to wrap it.
Below code wraps the first (text) node with a <mark> element and the last node with a <u> element:
const wrapNode = (nodeToWrap, wrapWith) => {
const range = document.createRange();
range.selectNode(nodeToWrap);
range.surroundContents(wrapWith);
}
wrapNode(document.querySelector('p').firstChild, document.createElement('mark'))
wrapNode(document.querySelector('p').lastChild, document.createElement('u'))
<p>
first node
<span>second node</span>
third node
</p>
From what I understand #Michal 's answer is vulnerable to XXS attacks (using innerHTML is a security vulnerability) Here is another link on this.
There are many ways to do this, one that I found and liked is:
function wrap_single(el, wrapper) {
el.parentNode.insertBefore(wrapper, el);
wrapper.appendChild(el);
}
let divWrapper;
let elementToWrap;
elementToWrap = document.querySelector('selector');
// wrapping the event form in a row
divWrapper = document.createElement('div');
divWrapper.className = 'row';
wrap_single(elementToWrap, divWrapper);
This works well. However for me, I sometimes want to just wrap parts of an element. So I modified the function to this:
function wrap_some_children(el, wrapper, counter) {
el.parentNode.insertBefore(wrapper, el);
if ( ! counter ) {
counter = el.childNodes.length;
}
for(i = 0; i < counter; i++) {
wrapper.appendChild( el.childNodes[0] );
}
}
// wrapping parts of the event form into columns
let divCol1;
let divCol2;
// the elements to wrap
elementToWrap = document.querySelector('selector');
// creating elements to wrap with
divCol1 = document.createElement('div');
divCol1.className = 'col-sm-6';
divCol2 = document.createElement('div');
divCol2.className = 'col-sm-6';
// for the first column
wrap_some_children(elementToWrap, divCol1, 13); // only wraps the first 13 child nodes
// for the second column
wrap_some_children(elementToWrap, divCol2);
I hope this helps.
wrapInner multiple tag content
function wilWrapInner(el, wrapInner) {
var _el = [].slice.call(el.children);
var fragment = document.createDocumentFragment();
el.insertAdjacentHTML('afterbegin', wrapInner);
var _wrap = el.children[0];
for (var i = 0, len = _el.length; i < len; i++) {
fragment.appendChild(_el[i]);
}
_wrap.appendChild(fragment);
}
Link Demo Jsbin

It is possible to comment and uncomment block of code from DOM tree using JQuery? [duplicate]

This sounds a little crazy, but I'm wondering whether possible to get reference to comment element so that I can dynamically replace it other content with JavaScript.
<html>
<head>
</head>
<body>
<div id="header"></div>
<div id="content"></div>
<!-- sidebar place holder: some id-->
</body>
</html>
In above page, can I get reference to the comment block and replace it with some content in local storage?
I know that I can have a div place holder. Just wondering whether it applies to comment block.
Thanks.
var findComments = function(el) {
var arr = [];
for(var i = 0; i < el.childNodes.length; i++) {
var node = el.childNodes[i];
if(node.nodeType === 8) {
arr.push(node);
} else {
arr.push.apply(arr, findComments(node));
}
}
return arr;
};
var commentNodes = findComments(document);
// whatever you were going to do with the comment...
console.log(commentNodes[0].nodeValue);
It seems there are legitimate (performance) concerns about using comments as placeholders - for one, there's no CSS selector that can match comment nodes, so you won't be able to query them with e.g. document.querySelectorAll(), which makes it both complex and slow to locate comment elements.
My question then was, is there another element I can place inline, that doesn't have any visible side-effects? I've seen some people using the <meta> tag, but I looked into that, and using that in <body> isn't valid markup.
So I settled on the <script> tag.
Use a custom type attribute, so it won't actually get executed as a script, and use data-attributes for any initialization data required by the script that's going to initialize your placeholders.
For example:
<script type="placeholder/foo" data-stuff="whatevs"></script>
Then simply query those tags - e.g.:
document.querySelectorAll('script[type="placeholder/foo"]')
Then replace them as needed - here's a plain DOM example.
Note that placeholder in this example isn't any defined "real" thing - you should replace that with e.g. vendor-name to make sure your type doesn't collide with anything "real".
Building off of hyperslug's answer, you can make it go faster by using a stack instead of function recursion. As shown in this jsPerf, function recursion is 42% slower on my Chrome 36 on Windows and 71% with IE11 in IE8 compatibility mode. It appears to run about 20% slower in IE11 in edge mode but faster in all other cases tested.
function getComments(context) {
var foundComments = [];
var elementPath = [context];
while (elementPath.length > 0) {
var el = elementPath.pop();
for (var i = 0; i < el.childNodes.length; i++) {
var node = el.childNodes[i];
if (node.nodeType === Node.COMMENT_NODE) {
foundComments.push(node);
} else {
elementPath.push(node);
}
}
}
return foundComments;
}
Or as done in TypeScript:
public static getComments(context: any): Comment[] {
const foundComments = [];
const elementPath = [context];
while (elementPath.length > 0) {
const el = elementPath.pop();
for (let i = 0; i < el.childNodes.length; i++) {
const node = el.childNodes[i];
if (node.nodeType === Node.COMMENT_NODE) {
foundComments.push(node);
} else {
elementPath.push(node);
}
}
}
return foundComments;
}
There is an API for document nodes traversal: Document#createNodeIterator():
var nodeIterator = document.createNodeIterator(
document.body,
NodeFilter.SHOW_COMMENT
);
// Replace all comment nodes with a div
while(nodeIterator.nextNode()){
var commentNode = nodeIterator.referenceNode;
var id = (commentNode.textContent.split(":")[1] || "").trim();
var div = document.createElement("div");
div.id = id;
commentNode.parentNode.replaceChild(div, commentNode);
}
#header,
#content,
#some_id{
margin: 1em 0;
padding: 0.2em;
border: 2px grey solid;
}
#header::after,
#content::after,
#some_id::after{
content: "DIV with ID=" attr(id);
}
<html>
<head>
</head>
<body>
<div id="header"></div>
<div id="content"></div>
<!-- sidebar placeholder: some_id -->
</body>
</html>
Edit: use a NodeIterator instead of a TreeWalker
If you use jQuery, you can do the following to get all comment nodes
comments = $('*').contents().filter(function(){ return this.nodeType===8; })
If you only want the comments nodes of the body, use
comments = $('body').find('*').contents().filter(function(){
return this.nodeType===8;
})
If you want the comment strings as an array you can then use map:
comment_strings = comments.map(function(){return this.nodeValue;})
Using document.evaluate and xPath:
function getAllComments(node) {
const xPath = "//comment()",
result = [];
let query = document.evaluate(xPath, node, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i = 0, length = query.snapshotLength; i < length; ++i) {
result.push(query.snapshotItem(i));
}
return result;
}
getAllComments(document.documentElement);
from my testing, using xPath is faster than treeWalker:
https://jsben.ch/Feagf
This is an old question, but here's my two cents on DOM "placeholders"
IMO a comment element is perfect for the job (valid html, not visible, and not misleading in any way).
However, traversing the dom looking for comments is not necessary if you build your code the other way around.
I would suggest using the following method:
Mark the places you want to "control" with markup of your choice (e.g a div element with a specific class)
<div class="placeholder"></div>
<div class="placeholder"></div>
<div class="placeholder"></div>
<div class="placeholder"></div>
<div class="placeholder"></div>
Find the placeholders the usual way (querySelector/classSelector etc)
var placeholders = document.querySelectorAll('placeholder');
Replace them with comments and keep reference of those comments:
var refArray = [];
[...placeholders].forEach(function(placeholder){
var comment = document.createComment('this is a placeholder');
refArray.push( placeholder.parentNode.replaceChild(comment, placeholder) );
});
at this stage your rendered markup should look like this:
<!-- this is a placeholder -->
<!-- this is a placeholder -->
<!-- this is a placeholder -->
<!-- this is a placeholder -->
<!-- this is a placeholder -->
Now you can access each of those comments directly with your built refArray and do whatevere it is you wanna do... for example:
replace the second comment with a headline
let headline = document.createElement('h1');
headline.innerText = "I am a headline!";
refArray[1].parentNode.replaceChild(headline,refArray[1]);
If you just want to get an array of all comments from a document or part of a document, then this is the most efficient way I've found to do that in modern JavaScript.
function getComments (root) {
var treeWalker = document.createTreeWalker(
root,
NodeFilter.SHOW_COMMENT,
{
"acceptNode": function acceptNode (node) {
return NodeFilter.FILTER_ACCEPT;
}
}
);
// skip the first node which is the node specified in the `root`
var currentNode = treeWalker.nextNode();
var nodeList = [];
while (currentNode) {
nodeList.push(currentNode);
currentNode = treeWalker.nextNode();
}
return nodeList;
}
I am getting over 50,000 operations per second in Chrome 80 and the stack and recursion methods both get less than 5,000 operations per second in Chrome 80. I had tens of thousands of complex documents to process in node.js and this worked the best for me.
https://jsperf.com/getcomments/6

Pure javascript method to wrap content in a div

I want to wrap all the nodes within the #slidesContainer div with JavaScript. I know it is easily done in jQuery, but I am interested in knowing how to do it with pure JS.
Here is the code:
<div id="slidesContainer">
<div class="slide">slide 1</div>
<div class="slide">slide 2</div>
<div class="slide">slide 3</div>
<div class="slide">slide 4</div>
</div>
I want to wrap the divs with a class of "slide" collectively within another div with id="slideInner".
If your "slide"s are always in slidesContainer you could do this
org_html = document.getElementById("slidesContainer").innerHTML;
new_html = "<div id='slidesInner'>" + org_html + "</div>";
document.getElementById("slidesContainer").innerHTML = new_html;
Like BosWorth99, I also like to manipulate the dom elements directly, this helps maintain all of the node's attributes. However, I wanted to maintain the position of the element in the dom and not just append the end incase there were siblings. Here is what I did.
var wrap = function (toWrap, wrapper) {
wrapper = wrapper || document.createElement('div');
toWrap.parentNode.appendChild(wrapper);
return wrapper.appendChild(toWrap);
};
How to "wrap content" and "preserve bound events"?
// element that will be wrapped
var el = document.querySelector('div.wrap_me');
// create wrapper container
var wrapper = document.createElement('div');
// insert wrapper before el in the DOM tree
el.parentNode.insertBefore(wrapper, el);
// move el into wrapper
wrapper.appendChild(el);
or
function wrap(el, wrapper) {
el.parentNode.insertBefore(wrapper, el);
wrapper.appendChild(el);
}
// example: wrapping an anchor with class "wrap_me" into a new div element
wrap(document.querySelector('div.wrap_me'), document.createElement('div'));
ref
https://plainjs.com/javascript/manipulation/wrap-an-html-structure-around-an-element-28
If you patch up document.getElementsByClassName for IE, you can do something like:
var addedToDocument = false;
var wrapper = document.createElement("div");
wrapper.id = "slideInner";
var nodesToWrap = document.getElementsByClassName("slide");
for (var index = 0; index < nodesToWrap.length; index++) {
var node = nodesToWrap[index];
if (! addedToDocument) {
node.parentNode.insertBefore(wrapper, node);
addedToDocument = true;
}
node.parentNode.removeChild(node);
wrapper.appendChild(node);
}
Example: http://jsfiddle.net/GkEVm/2/
A general good tip for trying to do something you'd normally do with jQuery, without jQuery, is to look at the jQuery source. What do they do? Well, they grab all the children, append them to a a new node, then append that node inside the parent.
Here's a simple little method to do precisely that:
const wrapAll = (target, wrapper = document.createElement('div')) => {
;[ ...target.childNodes ].forEach(child => wrapper.appendChild(child))
target.appendChild(wrapper)
return wrapper
}
And here's how you use it:
// wraps everything in a div named 'wrapper'
const wrapper = wrapAll(document.body)
// wraps all the children of #some-list in a new ul tag
const newList = wrapAll(document.getElementById('some-list'), document.createElement('ul'))
I like to manipulate dom elements directly - createElement, appendChild, removeChild etc. as opposed to the injection of strings as element.innerHTML. That strategy does work, but I think the native browser methods are more direct. Additionally, they returns a new node's value, saving you from another unnecessary getElementById call.
This is really simple, and would need to be attached to some type of event to make any use of.
wrap();
function wrap() {
var newDiv = document.createElement('div');
newDiv.setAttribute("id", "slideInner");
document.getElementById('wrapper').appendChild(newDiv);
newDiv.appendChild(document.getElementById('slides'));
}
jsFiddle
Maybe that helps your understanding of this issue with vanilla js.
To simply wrap a div without the need of the parent:
<div id="original">ORIGINAL</div>
<script>
document.getElementById('original').outerHTML
=
'<div id="wrap">'+
document.getElementById('original').outerHTML
+'</div>'
</script>
Working Example: https://jsfiddle.net/0v5eLo29/
More Practical Way:
const origEle = document.getElementById('original');
origEle.outerHTML = '<div id="wrap">' + origEle.outerHTML + '</div>';
Or by using only nodes:
let original = document.getElementById('original');
let wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
wrapper.append(original.cloneNode(true));
original.replaceWith(wrapper);
Working Example: https://jsfiddle.net/wfhqak2t/
A simple way to do this would be:
let el = document.getElementById('slidesContainer');
el.innerHTML = `<div id='slideInner'>${el.innerHTML}</div>`;
Note - below answers the title of the question but is not specific to the OP's requirements (which are over a decade old)
Using the range API is making wrapping easy, by creating a Range which selects only the node wished to be wrapped, and then use the surroundContents API to wrap it.
Below code wraps the first (text) node with a <mark> element and the last node with a <u> element:
const wrapNode = (nodeToWrap, wrapWith) => {
const range = document.createRange();
range.selectNode(nodeToWrap);
range.surroundContents(wrapWith);
}
wrapNode(document.querySelector('p').firstChild, document.createElement('mark'))
wrapNode(document.querySelector('p').lastChild, document.createElement('u'))
<p>
first node
<span>second node</span>
third node
</p>
From what I understand #Michal 's answer is vulnerable to XXS attacks (using innerHTML is a security vulnerability) Here is another link on this.
There are many ways to do this, one that I found and liked is:
function wrap_single(el, wrapper) {
el.parentNode.insertBefore(wrapper, el);
wrapper.appendChild(el);
}
let divWrapper;
let elementToWrap;
elementToWrap = document.querySelector('selector');
// wrapping the event form in a row
divWrapper = document.createElement('div');
divWrapper.className = 'row';
wrap_single(elementToWrap, divWrapper);
This works well. However for me, I sometimes want to just wrap parts of an element. So I modified the function to this:
function wrap_some_children(el, wrapper, counter) {
el.parentNode.insertBefore(wrapper, el);
if ( ! counter ) {
counter = el.childNodes.length;
}
for(i = 0; i < counter; i++) {
wrapper.appendChild( el.childNodes[0] );
}
}
// wrapping parts of the event form into columns
let divCol1;
let divCol2;
// the elements to wrap
elementToWrap = document.querySelector('selector');
// creating elements to wrap with
divCol1 = document.createElement('div');
divCol1.className = 'col-sm-6';
divCol2 = document.createElement('div');
divCol2.className = 'col-sm-6';
// for the first column
wrap_some_children(elementToWrap, divCol1, 13); // only wraps the first 13 child nodes
// for the second column
wrap_some_children(elementToWrap, divCol2);
I hope this helps.
wrapInner multiple tag content
function wilWrapInner(el, wrapInner) {
var _el = [].slice.call(el.children);
var fragment = document.createDocumentFragment();
el.insertAdjacentHTML('afterbegin', wrapInner);
var _wrap = el.children[0];
for (var i = 0, len = _el.length; i < len; i++) {
fragment.appendChild(_el[i]);
}
_wrap.appendChild(fragment);
}
Link Demo Jsbin

Categories