Reputation: 92581
I am aware that a large amount of DOM manipulation is bad due to it causing repaints ect.
but what about doing something like
var container = $('<div />');
{repeat:20}
container.append(<div>content</div>);
{endrepeat}
$('#actualElement').html(container.html());
even if it is not DOM manipulation, is it bad?
Upvotes: 2
Views: 315
Reputation: 816424
No, that is fine, as container
is not attached to the DOM. This is the preferred way to add a lot of elements to the DOM.
But by using html()
you will loose all event handlers or data
you add to the elements. If you want to keep them, consider using this:
$('#actualElement').empty().append(container.children());
You could also use a DocumentFragement, but as you are using jQuery, I would stick with jQuery.
Update: To answer the actual question: Yes, it is DOM manipulation, but you are adding to the DOM only once which is the best you can get (besides not inserting at all ;)).
Upvotes: 2
Reputation: 236022
Well, of course you are manipulating the DOM by inserting and creating new nodes. This will most likely cause a reflow, which is pretty slow, but probably not "bad".
If you want to create/change the markup you need to take that tradeoff.
As I mentioned in my comment, it's probably wrong to think about it in terms like "good" or "bad". If you want to change something on-the-fly via Javascript in the DOM, there is no way around to have a reflow at some point. Only thing you can do is, to avoid unecessary reflows/repaints by doing only one DOM access and doing the rest of your work in memory.
Upvotes: 0
Reputation: 1555
Yes, that is DOM manipulation. But it is likely faster than inserting the components one-by-one.
But in most browsers that should only repaint/reflow once (when you insert the built structure).
You should benchmark it, though, and compare it to other options (such as insert the HTML as a string).
Upvotes: 0
Reputation: 116110
No it is not bad.
Or, it is not worse (or better) than DOM manipulation regarding repaints. Actually, you are manipulating the DOM.
Assuming you're not just manipulating the DOM for fun, you will probably have a purpose to do so. If there are other solutions that don't require you to do DOM manipulation, those might be better, but if there aren't (or you can't find them), how can this solution be wrong if it does exactly what you need?
Upvotes: 0