Skip to content Skip to sidebar Skip to footer

What's The Effectiviest Way Of Creating An Element With Multiple Attributes And Appending It To Another Element And Have It Available As A Variable??

I wonder what's the effectiviest way of creating an element with id='id' class='class' attr='attr' .. and appending it to another element and have it available as a variable? So f

Solution 1:

var element = $("<div/>", {
    id: "id",
    class: "class",
    attr: "attr"
}).appendTo("#element");

appendTo returns a JQuery object, you can read more on http://api.jquery.com/appendTo/

Edit: It looks like you're asking if an effective way to create elements is having methods for all HTML tags, so that your library doesn't have to do any sort of text parsing/regex.

This isn't a solution as it makes development a lot slower.

Solution 2:

One way is to use a function and DOM methods:

<scripttype="text/javascript">var elementData = {
  tagName: 'div',
  properties: {
    id: 'div0',
    onclick: function(){alert(this.id);},
    className: 'someClass'
  },
  content: '<h1>New Div</h1>'
}


functionelementBuilder(obj) {
  var el = document.createElement(obj.tagName);
  var props = obj.properties;

  for (var p in props) {
    if (props.hasOwnProperty(p)) {
      el[p] = props[p];
    }
  }

  if (typeof obj.content == 'string') {
    el.innerHTML = obj.content;
  }
  return el;
}

</script><buttononclick="
  var newElement = elementBuilder(elementData);
  document.body.insertBefore(newElement, this.nextSibling);
">Insert element</button>

The above could be expanded to create more than one element per call, I'll leave that you.

Another method is to take an HTML string, convert it to an element (or elements) and return it in a document fragment:

<scripttype="text/javascript">var htmlString = '<p><b>paragraph</b></p>' +
                 '<p>Another p</p>';

functionbyInnerHTML(s) {
  var d = document.createElement('div');
  d.innerHTML = s;
  var frag = document.createDocumentFragment();

  while (d.firstChild) {
    frag.appendChild(d.firstChild);
  }
  return frag;
}

</script><buttononclick="
  var newContent = byInnerHTML(htmlString);
  document.body.insertBefore(newContent, this.nextSibling);
">Insert element</button>

The second one returns a document fragment that can be inserted into the page. Of course if you want to generate parts of a table, the second method isn't quite so good.

Solution 3:

In tune with a pure JavaScript implementation, here's my take on the problem:

functioncreateElement(type, attributes, parent){
    var node = document.createElement(type);

    for (i in attributes){
        node.setAttribute(i, attributes[i])
    }

    if (parent && parent.__proto__.appendChild){
        parent.appendChild(node)
    }

    return node;
}

And you use it like this:

createElement("span", { "id": "theID", "class": "theClass", "title": "theAttribute"}, document.getElementById("theParent"))

I kept one of your initial requirements: append the node to some other element and also return it.

I particularly like RobG's second example with the fragment. Definitely something I'd try if I were using plain strings to represent HTML.

If it doesn't warrant the use-case, it doesn't always make sense to import a JS framework. jQuery is no exception. Should you decide more complex workflows are needed, that's your warrant! ;)

Post a Comment for "What's The Effectiviest Way Of Creating An Element With Multiple Attributes And Appending It To Another Element And Have It Available As A Variable??"