0

I'm tinkering with writing a more efficient methodology in the creation of dynamically generated DOM elements via JavaScript. This is something I intend to add into my own JS framework later on. Looking for other OOP devs that could help better refine what I do have.

Here's a link to the working CodePen: http://codepen.io/DaneTheory/pen/yeLvmm/

Here's the JS:

    function CreateDOMEl() {};
    CreateDOMEl.prototype.uiFrag = document.createDocumentFragment();
    CreateDOMEl.prototype.elParent = function(elParent, index) {
        this.elParent = document.getElementsByTagName(elParent)[index];
    }
    CreateDOMEl.prototype.elType = function(type) {
        newEl = document.createElement(type);
        this.uiFrag.appendChild(newEl);
    }
    CreateDOMEl.prototype.elContent = function(elContent) {
        this.elContent = elContent;
        newEl.textContent = elContent;
    }
    CreateDOMEl.prototype.buildEl = function() {
        this.elParent.appendChild(this.uiFrag);
    }
        var div = new CreateDOMEl();
            div.elParent('body', 0);
            div.elType('DIV');
            div.elContent('OK');
            div.buildEl();
            console.log(div);
        var bttn = new CreateDOMEl();
            bttn.elParent('body', 0);
            bttn.elType('BUTTON');
            bttn.elContent('SUBMIT');
            bttn.buildEl();
            console.log(bttn);

And some CSS to get elements to appear on page:

    div {
         width:100px;
         height:100px;
         border: 1px solid red;   
        }

My thoughts:

  • For performance, using the prototype to build methods versus placing all the logic in the constructor.
  • Rather than directly appending elements to the page, append to a single Document Fragment. Once the element is built out as a Doc Frag, appending the Doc Frag to to the DOM. I like this method for performance, but would like to improve upon it. Any useful implementations of requestnimationFrame, or using range and other versions of the document fragment method?
  • Silly, but I think for debugging it'd be nice to see the generated Element type within the Object property's on console log. As of right now, console logging a created element will show the elements parent and text content. It'd be great to show the elements type as well.
  • Creating more than one element at a time is another piece of functionality I'd like to offer as an option. For instance, creating a div element creates one div element. What's a good way to add another optional method to create multiple instances of div's.

    div.elType('DIV');
    // After calling the elType method, do something like this:
    div.elCount(20);
    // This would create 20 of the same divs
    
  • Lastly, a nice clean way to optionally add attributes (i.e: classes, an ID, value, a placeholder, custom attributes, data-* attributes, etc.). I've got a nice helper function I use that adds multiple attributes to an element in an object literal syntax looking way. Adding this as a method of the constructor would be ideal. Here's that function:

        function setAttributes(el, attrs) {
            for(var key in attrs) {
                el.setAttribute(key, attrs[key]);
            }
        }
        // A use case using the above
        // function would be:
        var anInputElement = document.createElement("TEXTAREA");
            setAttributes(anInputElement, {
                "type": "text",
                "id": "awesomeID",
                "name": "coolName",
                "placeholder": "Hey I'm some placeholder example text",
                "class": "awesome"
            });
        // Which creates the following HTML snippet:
        <textarea type="text" id="awesomeID" name="coolName" placeholder="Hey I'm some placeholder example text" class="awesome">
    

As a side note, realizing now that the above helper function needs rewritten so that multiple classes could be created.

DaneTheory
  • 282
  • 3
  • 16
  • `new CreateDOMEl()` doesn't look very cool by the way. – Marco Bonelli Dec 06 '15 at 01:08
  • So what's your question? I see no question here at all. This isn't the place for discussing ideas. –  Dec 06 '15 at 01:10
  • Are you referencing the use of the "new" operator, or the the name of the constructor itself "CreateDOMEl"? If it's the former, that's a long time debate. Personally, I find it visually useful when used in conjunction with a capitalized constructor function. If it's the latter, yea I'll get creative with naming things after the functionality is done. It would be helpful to provide a solution with your comment in the future. Thanks though. – DaneTheory Dec 06 '15 at 01:21
  • tl;dr: Questions are: Can this be written in a more performant way? Can Document Fragment be used more efficiently? How to get dynamically created element type to appear as property of console logged object? How to write method that can create multiple of the same element? How to write the helper function provided as a method for adding attributes? – DaneTheory Dec 06 '15 at 01:27

1 Answers1

1

Respectfully, I believe you may be overthinking it. Just use the tools available in JavaScript and get 'er done. In terms of performance, computers are so fast at running your JavaScript that you (and me) are unable to perceive, or even comprehend, the speed. Here's how I add a link to an MDL nav menu, for example. It's just vanilla JS. Don't forget to add event listeners.

  function navMenuAdd(type,text){
    var newAnchor = doc.createElement("anchor");
    newAnchor.classList.add('mdl-navigation__link');
    newAnchor.classList.add(type);
    newAnchor.href = "javascript:void(0)";
    var anchorContent = doc.createTextNode(text);
    newAnchor.appendChild(anchorContent);
    newAnchor.addEventListener('click', navMenuClickHandler, false);
    //newAnchor.style.display = 'none';
    if (type === 'Thingy A'){
      //insertAfter(newAnchor, navMenuCredentials);
      navMenuCredentialsPanel.appendChild(newAnchor);
    } else if (type === 'Thingy B'){
      //insertAfter(newAnchor, navMenuDevices);
      navMenuDevicesPanel.appendChild(newAnchor);
    }
  }
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
  • Thank you sir. You have saved hours of my time! The way you describe, the event listeners work and I can generate elements using a for loop, passing the relevant parameters in that function! – Petr L. Oct 06 '22 at 16:30