Is there any way to find an element in a documentFragment? - javascript

var oFra = document.createDocumentFragment();
// oFra.[add elements];
document.createElement("div").id="myId";
oFra.getElementById("myId"); //not in FF
How can I get "myId" before attaching fragment to document?

All of these answers are rather old, from back when querySelectorAll and querySelector were not widely available. It should be noted that these two functions which accept CSS selectors as parameters do work on DocumentFragments in modern browsers, and should be the preferred way of dealing with the situation in the question. The alternate solutions presented in some of the answers would be a good approach for legacy browsers which did not support querySelectorAll or querySelector.
Here is an example usage:
var df = document.createDocumentFragment();
var div = document.createElement('div');
div.id = 'foo';
df.appendChild(div);
var result = df.querySelector('#foo'); // result contains the div element
A good implementation should first use object detection to see if the browser supports this. For instance:
function getElementByIdInFragment(fragment, id) {
if (fragment.querySelector) {
return fragment.querySelector('#' + id);
} else {
// your custom implementation here
}
}

No. The DocumentFragment API is minimal to say the least: it defines no properties or methods, meaning that it only supports the properties and methods defined in the Node API. As methods such as getElementById are defined in the Document API, they cannot be used with a DocumentFragment.

NickFitz is right, DocumentFragment doesn't have the API you expect from Document or Element, in the standard or in browsers (which is a shame; it would be really handy to be able to set a fragment's innerHTML.
Even frameworks don't help you here, as they tend to require Nodes be in the document, or otherwise use methods on the context node that don't exist on fragments. You'd probably have to write your own, eg.:
function Node_getElementById(node, id) {
for (var i= 0; i<node.childNodes.length; i++) {
var child= node.childNodes[i];
if (child.nodeType!==1) // ELEMENT_NODE
continue;
if (child.id===id)
return child;
child= Node_getElementById(child, id);
if (child!==null)
return child;
}
return null;
}
It would almost certainly be better to keep track of references as you go along than to rely on a naïve, poorly-performing function like the above.
var frag= document.createDocumentFragment();
var mydiv= document.createElement("div");
mydiv.id= 'myId';
frag.appendChild(mydiv);
// keep reference to mydiv

What about:
var oFra = document.createDocumentFragment();
var myDiv = document.createElement("div");
myDiv.id="myId";
oFra.appendChild(myDiv);
oFra.getElementById("myId"); //not in FF
Unless you've added the the created div to your document fragment I'm not sure why getElementById would find it?
--edit
If you're willing to roll your own getElementById function then you ought to be able to get the reference you're after, because this code works:
var oFra = document.createDocumentFragment();
var myDiv = document.createElement("div");
myDiv.id = "myId";
oFra.appendChild(myDiv);
if (oFra.hasChildNodes()) {
var i=0;
var myEl;
var children = oFra.childNodes;
for (var i = 0; i < children.length; i++) {
if (children[i].id == "myId") {
myEl = children[i];
}
}
}
window.alert(myEl.id);

Using jQuery:
// Create DocumentFragment
var fragment = document.createDocumentFragment(),
container = document.createElement('div');
container.textContent = 'A div full of text!';
container.setAttribute('id', 'my-div-1');
container.setAttribute('class', 'a-div-class');
fragment.appendChild(container);
// Query container's class when given ID
var div = $('<div></div>').html(fragment);
console.log(div.find('#my-div-1').attr('class'));
jsFiddle: http://jsfiddle.net/CCkFs/
You have the overhead of creating the div with jQuery, though. A little hacky, but it works.

The best way by far to find out what you can and can't do with a DocumentFragment is to examine its prototype:
const newFrag = document.createDocumentFragment();
const protNewFrag = Object.getPrototypeOf( newFrag );
console.log( '£ protNewFrag:' );
console.log( protNewFrag );
I get
DocumentFragmentPrototype { getElementById: getElementById(),
querySelector: querySelector(), querySelectorAll: querySelectorAll(),
prepend: prepend(), append: append(), children: Getter,
firstElementChild: Getter, lastElementChild: Getter,
childElementCount: Getter, 1 more… }
... which tells me I can do things like:
const firstChild = newFrag.children[ 0 ];
PS this won't work:
const firstChild = Object.getPrototypeOf( newFrag ).children[ 0 ];
... you'll be told that "the object doesn't implement the DocumentFragment interface"

An external source, listed below, showed the following code snippet:
var textblock=document.createElement("p")
textblock.setAttribute("id", "george")
textblock.setAttribute("align", "center")
Which displays a different way of setting the object's ID parameter.
Javascript Kit - Document Object Methods

My DOM has a #document-fragment under the element tag.
This is what I am using (using jQuery) , Also I have a use case where I have the HTML DOM in a string -
var texttemplate = $(filecontents).find('template').html();
$(texttemplate).children()
<p>​Super produced One​</p>​,
<appler-one>​</appler-one>,
<p>​Super produced Two​</p>,
<appler-two>​…​</appler-two>]
$(texttemplate).html()
"<p>Super produced One</p>
<appler-one></appler-one>
<p>Super produced Two</p>
<appler-two>
<p>Super produced Three</p>
<appler-three></appler-three>
</appler-two>"
$(texttemplate).find("appler-one")
[<appler-one>​</appler-one>​]

Related

Alter unappened element's html tag type with javascript

So I have an element created by another process, created in a method akin to
var their_element = document.createElement("div");
/* Lots of stuff is done to their_element */
And that object is being passed to me later. It has not been appended anywhere yet. The problem is, I need it to be different html tag type when it finally hits the html, such as:
<form></form>
How do i change it? The solutions I have found involve editing after it's appended, not before.
Edit:
Also, learned nodeName can't be assigned for this.
their_element.nodeName = "FORM"
doesn't work.
Also, this doesn't work either:
their_element.tagName = "FORM"
Also this didn't work either:
var outside = their_element.outerHTML;
outside = outside.replace(/div/g, 'form');
their_element.outerHTML = outside;
All of these still leave it as a DIV when appended.
(And I'm not looking for jQuery)
Check on this for cross-browser compatability, but there are properties and methods on elements that could be of use. Particularly, Element.attributes, Element.hasAttributes(), and Element.setAttribute(). See: https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes
I'm not going to use ES6 here, so we don't have to worry about transpiling. You can update if you want:
var el = document.createElement('div');
el.id="random";
el.style.background="red";
el.style.width="200px";
el.style.padding="10px";
el.style.margin="10px";
el.innerHTML="<input type='submit' value='submit'>";
console.log({"Element 1": el});
var newEl = document.createElement('form');
console.log({"Element 2 Before Transformation": newEl})
if (el.hasAttributes()) {
var attr = el.attributes
for (var i = 0; i < attr.length; i++) {
var name = attr[i].name, val = attr[i].value;
newEl.setAttribute(name, val)
}
}
if (el.innerHTML) { newEl.innerHTML = el.innerHTML }
console.log({"Element 2 After Transformation": newEl})
document.body.append(el);
document.body.append(newEl);
There are certain properties you need to account for like innerHTML, innerText, and textContent that would overwrite one another if multiples are set. You may also have to account for childNodes and what not.

Counting parent nodes

Is there a native method of DOM element in ECMAScript that will allow to count all ancestors of a given element (up to window object or DOM element specified by Id,Name etc.)?
Example use is to check all ancestors of a given element and remove a specified attribute.
There is the node iterator ( https://developer.mozilla.org/en-US/docs/Web/API/NodeIterator ) which could be used for this purpose
You can use xpath:
document.evaluate('ancestor::*', x, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null)
See https://developer.mozilla.org/en/docs/Introduction_to_using_XPath_in_JavaScript for more details.
I've wrote a simple function that does an action described in a question. It gets all ancestors of a given element and removes a given attribute from every element that is between "starting" and "ending" element (it does not perform an removeAttribute method on "ending" element).
var modifyAncestors = function(startingelementid,endingelementId,searchedattribute) {
var nodecount = document.getElementById(endingelementId).childNodes.length;
console.log(nodecount);
var currentid = startingelementid;
console.log(currentid);
console.log(searchedattribute);
for(var i = 0; i < nodecount; i++) {
if(currentid == endingelementId) {
break;
}
else {
document.getElementById(currentid).removeAttribute(searchedattribute);
currentid = document.getElementById(currentid).parentNode.id;
}
}
}
Working example: http://www.blacktieseo.com/so/js/test.html (couldn't get it to work with Fiddle JS).
Any comments, bugs etc. will be highly appreciated.

Create reusable document fragment from the DOM

I would like to have a document fragment/element on the shelf to which I've connected a bunch of other elements. Then whenever I want to add one of these element-systems to the DOM, I copy the fragment, add the unique DOM ID and attach it.
So, for example:
var doc = document,
prototype = doc.createElement(), // or fragment
ra = doc.createElement("div"),
rp = doc.createElement("div"),
rp1 = doc.createElement("a"),
rp2 = doc.createElement("a"),
rp3 = doc.createElement("a");
ra.appendChild(rp);
rp.appendChild(rp1);
rp.appendChild(rp2);
rp.appendChild(rp3);
rp1.className = "rp1";
rp2.className = "rp2";
rp3.className = "rp3";
prototype.appendChild(ra);
This creates the prototype. Then I want to be able to copy the prototype, add an id, and attach. Like so:
var fr = doc.createDocumentFragment(),
to_use = prototype; // This step is illegal, but what I want!
// I want prototype to remain to be copied again.
to_use.id = "unique_id75";
fr.appendChild(to_use);
doc.getElementById("container").appendChild(fr);
I know it's not legal as it stands. I've done fiddles and researched and so on, but it ain't working. One SO post suggested el = doc.appendChild(el); returns el, but that didn't get me far.
So... is it possible? Can you create an on-the-shelf element which can be reused? Or do you have to build the DOM structure you want to add from scratch each time?
Essentially I'm looking for a performance boost 'cos I'm creating thousands of these suckers :)
Thanks.
Use Node.cloneNode:
var container = document.getElementById('container');
var prototype = document.createElement('div');
prototype.innerHTML = "<p>Adding some <strong>arbitrary</strong> HTML in"
+" here just to illustrate.</p> <p>Some <span>nesting</span> too.</p>"
+"<p>CloneNode doesn't care how the initial nodes are created.</p>";
var prototype_copy = prototype.cloneNode(true);
prototype_copy.id = 'whatever'; //note--must be an Element!
container.appendChild(prototype_copy);
Speed Tips
There are three operations you want to minimize:
String Parsing
This occurs when you use innerHTML. innerHTML is fast when you use it in isolation. It's often faster than the equivalent manual-DOM construction because of the overhead of all those DOM method calls. However, you want to keep innerHTML out of inner loops and you don't want to use it for appending. element.innerHTML += 'more html' in particular has catastrophic run-time behavior as the element's contents get bigger and bigger. It also destroys any event or data binding because all those nodes are destroyed and recreated.
So use innerHTML to create your "prototype" nodes for convenience, but for inner loops use DOM manipulation. To clone your prototypes, use prototype.cloneNode(true) which does not invoke the parser. (Be careful with id attributes in cloned prototypes--you need to make sure yourself that they are unique when you append them to the document!)
Document tree modification (repeated appendChild calls)
Every time you modify the document tree you might trigger a repaint of the document window and update the document DOM node relationships, which can be slow. Instead, batch your appends up into a DocumentFragment and append that to the document DOM only once.
Node lookup
If you already have an in-memory prototype object and want to modify pieces of it, you will need to navigate the DOM to find and modify those pieces whether you use DOM traversal, getElement*, or querySelector*.
Keep these searches out of your inner loops by keeping a reference to the nodes you want to modify when you create the prototype. Then whenever you want to clone a near-identical copy of the prototype, modify the nodes you have references to already and then clone the modified prototype.
Sample Template object
For the heck of it, here is a basic (and probably fast) template object illustrating the use of cloneNode and cached node references (reducing the use of string parsing and Node lookups).
Supply it with a "prototype" node (or string) with class names and data-attr="slotname attributename" attributes. The class names become "slots" for text-content replacement; the elements with data-attr become slots for attribute name setting/replacement. You can then supply an object to the render() method with new values for the slots you have defined, and you will get back a clone of the node with the replacements done.
Example usage is at the bottom.
function Template(proto) {
if (typeof proto === 'string') {
this.proto = this.fromString(proto);
} else {
this.proto = proto.cloneNode(true);
}
this.slots = this.findSlots(this.proto);
}
Template.prototype.fromString = function(str) {
var d = document.createDocumentFragment();
var temp = document.createElement('div');
temp.innerHTML = str;
while (temp.firstChild) {
d.appendChild(temp.firstChild);
}
return d;
};
Template.prototype.findSlots = function(proto) {
// textContent slots
var slots = {};
var tokens = /^\s*(\w+)\s+(\w+)\s*$/;
var classes = proto.querySelectorAll('[class]');
Array.prototype.forEach.call(classes, function(e) {
var command = ['setText', e];
Array.prototype.forEach.call(e.classList, function(c) {
slots[c] = command;
});
});
var attributes = proto.querySelectorAll('[data-attr]');
Array.prototype.forEach.call(attributes, function(e) {
var matches = e.getAttribute('data-attr').match(tokens);
if (matches) {
slots[matches[1]] = ['setAttr', e, matches[2]];
}
e.removeAttribute('data-attr');
});
return slots;
};
Template.prototype.render = function(data) {
Object.getOwnPropertyNames(data).forEach(function(name) {
var cmd = this.slots[name];
if (cmd) {
this[cmd[0]].apply(this, cmd.slice(1).concat(data[name]));
}
}, this);
return this.proto.cloneNode(true);
};
Template.prototype.setText = (function() {
var d = document.createElement('div');
var txtprop = (d.textContent === '') ? 'textContent' : 'innerText';
d = null;
return function(elem, val) {
elem[txtprop] = val;
};
}());
Template.prototype.setAttr = function(elem, attrname, val) {
elem.setAttribute(attrname, val);
};
var tpl = new Template('<p data-attr="cloneid id">This is clone number <span class="clonenumber">one</span>!</p>');
var tpl_data = {
cloneid: 0,
clonenumber: 0
};
var df = document.createDocumentFragment();
for (var i = 0; i < 100; i++) {
tpl_data.cloneid = 'id' + i;
tpl_data.clonenumber = i;
df.appendChild(tpl.render(tpl_data));
}
document.body.appendChild(df);
I'd be shocked if innerHTML wasn't faster. Pre-compiled templates such as those provided by lo-dash or doT seem like a great way to go!
Check out this simple example:
http://jsperf.com/lodash-template
It shows you can get 300,000 ops/sec for a fairly complex template with a loop using lo-dash's pre-compiled templates. Seems pretty fast to me and way cleaner JS.
Obviously, this is only one part of the problem. This generates the HTML, actually inserting the HTML is another problem, but once again, innerHTML seems to win over cloneNode and other DOM-based approaches and generally the code is way cleaner.
http://jsperf.com/clonenode-vs-innerhtml-redo/2
Obviously you can take these benchmarks worth a grain of salt. What really matters is your actual app. But I'd recommend giving multiple approaches a try and benchmarking them yourself before making up your mind.
Note: A lot of the benchmarks about templates on JSPerf are doing it wrong. They're re-compiling the template on every iteration, which is obviously going to be way slow.

jQuery appending an array of elements

For the purpose of this question lets say we need to append() 1000 objects to the body element.
You could go about it like this:
for(x = 0; x < 1000; x++) {
var element = $('<div>'+x+'</div>');
$('body').append(element);
}
This works, however it seems inefficient to me as AFAIK this will cause 1000 document reflows. A better solution would be:
var elements = [];
for(x = 0; x < 1000; x++) {
var element = $('<div>'+x+'</div>');
elements.push(element);
}
$('body').append(elements);
However this is not an ideal world and this throws an error Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]. I understand that append() can't handle arrays.
How would I using jQuery (I know about the DocumentFragment node, but assume I need to use other jQuery functions on the element such as .css()) add a bunch of objects to the DOM at once to improve performance?
You could use an empty jQuery object instead of an array:
var elements = $();
for(x = 0; x < 1000; x++) {
elements = elements.add('<div>'+x+'</div>');
// or
// var element = $('<div>'+x+'</div>');
// elements = elements.add(element);
}
$('body').append(elements);
This might be useful if you want to do stuff with newly generated element inside the loop. But note that this will create a huge internal stack of elements (inside the jQuery object).
It seems though that your code works perfectly fine with jQuery 1.8.
You could just call
$('body').append(elements.join(''));
Or you can just create a large string in the first place.
var elements = '';
for(x = 0; x < 1000; x++) {
elements = elements + '<div>'+x+'</div>';
}
$(document.body).append(elements);
Like you mentioned, probably the most "correct" way is the usage of a DocFrag. This could look like
var elements = document.createDocumentFragment(),
newDiv;
for(x = 0; x < 1000; x++) {
newDiv = document.createElement('div');
newDiv.textContent = x;
elements.append( newDiv );
}
$(document.body).append(elements);
.textContent is not supported by IE<9 and would need an conditional check to use .innerText or .text instead.
Upgrade to jQuery 1.8, this works as intended:
​$('body')​.append([
'<b>1</b>',
'<i>2</i>'
])​;​
Since $.fn.append takes a variable number of elements we can use apply to pass the array as arguments to it:
el.append.apply(el, myArray);
This works if you have an array of jQuery objects. According to the spec though you can append an array of elements if you have the DOM elements. If you have an array of html strings you can just .join('') them and append them all at once.
A slight change to your second approach:
var elements = [],
newDiv;
for (x = 0; x < 1000; x++) {
newDiv = $('<div/>').text(x);
elements.push(newDiv);
}
$('body').append(elements);
$.append() certainly can append an array: http://api.jquery.com/append/
.append(content) | content: One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.
Sometimes, jQuery isn't the best solution. If you have a lot of elements to append to the DOM, documentFragment is a viable solution:
var fragment = document.createDocumentFragment();
for(var i = 0; i < 1000; i++) {
fragment.appendChild(document.createElement('div'));
}
document.getElementsByTagName('body')[0].appendChild(fragment);
If you're going for raw performance then I would suggest pure JS, though some would argue that your development performance is more important than your site's/program performance.
Check this link for benchmarks and a showcase of different DOM insertion techniques.
edit:
As a curiosity, documentFragment proves to be one of the slowest methods.
I would use native Javascript, normally much faster:
var el = document.getElementById('the_container_id');
var aux;
for(x = 0; x < 1000; x++) {
aux = document.createElement('div');
aux.innerHTML = x;
el.appendChild(aux);
}
EDIT:
There you go a jsfiddle with different options implemented. The #jackwander's solution is, clearly, the most effective one.
I know, the question is old, but maybe it helps others.
Or simple use ECMA6 spread operator:
$('body').append(...elements);

Getting element by a custom attribute using JavaScript

I have an XHTML page where each HTML element has a unique custom attribute, like this:
<div class="logo" tokenid="14"></div>
I need a way to find this element by ID, similar to document.getElementById(), but instead of using a general ID, I want to search for the element using my custom "tokenid" attribute. Something like this:
document.getElementByTokenId('14');
Is that possible? If yes - any hint would be greatly appreciated.
Thanks.
It is not good to use custom attributes in the HTML. If any, you should use HTML5's data attributes.
Nevertheless you can write your own function that traverses the tree, but that will be quite slow compared to getElementById because you cannot make use of any index:
function getElementByAttribute(attr, value, root) {
root = root || document.body;
if(root.hasAttribute(attr) && root.getAttribute(attr) == value) {
return root;
}
var children = root.children,
element;
for(var i = children.length; i--; ) {
element = getElementByAttribute(attr, value, children[i]);
if(element) {
return element;
}
}
return null;
}
In the worst case, this will traverse the whole tree. Think about how to change your concept so that you can make use browser functions as much as possible.
In newer browsers you use of the querySelector method, where it would just be:
var element = document.querySelector('[tokenid="14"]');
This will be much faster too.
Update: Please note #Andy E's comment below. It might be that you run into problems with IE (as always ;)). If you do a lot of element retrieval of this kind, you really should consider using a JavaScript library such as jQuery, as the others mentioned. It hides all these browser differences.
<div data-automation="something">
</div>
document.querySelector("div[data-automation]")
=> finds the div
document.querySelector("div[data-automation='something']")
=> finds the div with a value
If you're using jQuery, you can use some of their selector magic to do something like this:
$('div[tokenid=14]')
as your selector.
You can accomplish this with JQuery:
$('[tokenid=14]')
Here's a fiddle for an example.
If you're willing to use JQuery, then:
var myElement = $('div[tokenid="14"]').get();
Doing this with vanilla JavaScript will do the trick:
const something = document.querySelectorAll('[data-something]')
Use this more stable Function:
function getElementsByAttribute(attr, value) {
var match = [];
/* Get the droids we are looking for*/
var elements = document.getElementsByTagName("*");
/* Loop through all elements */
for (var ii = 0, ln = elements.length; ii < ln; ii++) {
if (elements[ii].nodeType === 1){
if (elements[ii].name != null){
/* If a value was passed, make sure it matches the elements */
if (value) {
if (elements[ii].getAttribute(attr) === value)
match.push(elements[ii]);
} else {
/* Else, simply push it */
match.push(elements[ii]);
}
}
}
}
return match;
};

Categories

Resources