lukek
lukek

Reputation: 478

Dom Manipulation. All changes at once

I have a simple module that I have written. The purpose is to create links on the page with any url under a certain class name

Below is the main function which does all the dirty work

generateLinks: function(){
    $('.link-gen').each(function(index, item){
        var replace = $(item).html().replace(_regEx, _linkMarkUp);
        $(item).html(replace);
    });
}

It is my understanding that I should be trying to apply all dom changes at once so I don't need to continually access the dom. How would I go about doing this if I am possibly modifying many different links on the page?

Upvotes: 1

Views: 220

Answers (1)

jfriend00
jfriend00

Reputation: 708046

I'll try to answer the specifics of your question.

If you need to modify N separate elements in the page, your options are:

  1. Get the HTML of a common parent that contains the HTML of all the N separate elements and use some sort of search and replace on the RAW HTML to find the parts you want to change in each targeted element. Then set that changed HTML back on the common parent.

  2. Do the same thing as in the above step for the entire body HTML.

  3. Find each object you need to modify in the DOM and change its HTML directly (as your current code does).

While options 1 and 2 are fewer DOM manipulations, they are generally a bad way to do things because you are asking the browser to do lots of heavy work, throwing away lots of existing DOM objects, parsing raw HTML from scratch again and then creating lots of new DOM objects. This also has the side effect of wiping out all existing event handlers in that HTML (because they are all new DOM objects). So 1 and 2 are NOT recommended in most cases.

That leaves you with option 3 which is what you are already doing. For modifying N separate objects, use N DOM manipulations - one on each object.


What I suspect the comment you read is meant to address is that something like this would be a bad thing (lots of DOM manipulations, but all on one object):

var item = $("#foo");
for (var i = 0; i < collection.length; i++) {
    item.html(item.html() + "<br"> + collection[i]);
}

when something like this would be a lot better (one DOM manipulation):

var item = $("#foo");
var newText = "";
for (var i = 0; i < collection.length; i++) {
    newText += "<br"> + collection[i];
}
item.html(item.html() + newText);

Upvotes: 1

Related Questions