jQuery.create() – jQuery plugin to create HTML elements

21 באוגוסט 2008

תגיות: , , , ,
26 תגובות

jQuery.create() – it's a featured plugin for jQuery JavaScript Library.
You can create any types of HTML elements, set attributes and context or HTML using jQuery.create().
See below the HTML example declaration.

I think it make easy and fast your programming in JavaScript.

jQuery.create = function() {
if (arguments.length == 0) return [];
var args = arguments[0] || {}, elem = null, elements = null;
var siblings = null;

// In case someone passes in a null object,
// assume that they want an empty string.
if (args == null) args = "";
if (args.constructor == String) {
if (arguments.length > 1) {
var attributes = arguments[1];
if (attributes.constructor == String) {
elem = document.createTextNode(args);
elements = [];
elements.push(elem);
siblings =
jQuery.create.apply(null, Array.prototype.slice.call(arguments, 1));
elements = elements.concat(siblings);
return elements;

} else {
elem = document.createElement(args);

// Set element attributes.
var attributes = arguments[1];
for (var attr in attributes)
jQuery(elem).attr(attr, attributes[attr]);

// Add children of this element.
var children = arguments[2];
children = jQuery.create.apply(null, children);
jQuery(elem).append(children);

// If there are more siblings, render those too.
if (arguments.length > 3) {
siblings =
jQuery.create.apply(null, Array.prototype.slice.call(arguments, 3));
return [elem].concat(siblings);
}
return elem;
}
} else return document.createTextNode(args);
} else {
elements = [];
elements.push(args);
siblings =
jQuery.create.apply(null, (Array.prototype.slice.call(arguments, 1)));
elements = elements.concat(siblings);
return elements;
}
};

HTML example declaration.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript"
src="../App_Scripts/jQuery/jQuery-1.2.3.js"></script>
<!-- Utils.js - contain jQuery.create - plug-in -->
<script type="text/javascript"
src="../App_Scripts/Utils/Utils.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Create new element typeof DIV
var o = $.create('div',
{'id':'wrapper-header',
'class':'header'}, ['Hello world!!!']);

// Append object o
$('#wrapper').append($(o));
});
</script>
</head>
<body>

<div id="wrapper"></div>

</body>
</html>
הוסף תגובה
facebook linkedin twitter email

להגיב על kelly לבטל

האימייל לא יוצג באתר. שדות החובה מסומנים *

26 תגובות

  1. Rick11 בנובמבר 2008 ב 14:45

    I made some adjustment to your plugin to make it more crossbrowser. E.g. IE does not allow to create input elements with attributes at runtime. Changes can be found here:

    http://www.internetschoon.nl/viewSingleItem/3563/Create-elements-via-DOM-and-jQuery.htm

    הגב
  2. kelly27 בינואר 2009 ב 7:49

    Or you could just do the same thing with the normal library by doing

    jQuery("

    " )
    .attr( "id", "wrapper-header")
    .addClass( "header" )
    .html( "hello world")
    .appendTo( jQuery( "#wrapper" ) );

    הגב
  3. Jon Davis9 בפברואר 2009 ב 0:18

    I don't get it. $('#wrapper").append('

    hellow world

    ');

    הגב
  4. Fabio24 ביולי 2009 ב 3:59

    how to create an element out of expressions like: "div#1.fabio" would become:

    הגב
  5. sander17 בנובמבר 2009 ב 16:34

    how can i create several objects in each other?
    like this for example:

    var o = $.create('div', {'id':'tooltip'}, [
    $.create('h1', {'id':'title'}, [ 'text']),
    $.create('p', {'id':'tekst'}, [ 'text']])
    ]);

    $(this).append($(o));

    it gives an error right now (Node cannot be inserted at the specified point in the hierarchy)

    plug in is great. really clean!

    thnx

    הגב
  6. Basil Goldman2 בדצמבר 2009 ב 11:15

    $.create('div', { }, [ — this is HTML or TEXT only — ] );

    But you can try this (See below)

    var el = jQuery(
    $.create('div', {}, [])
    ).append(
    $.create('span',{}, ['Hello']),
    $.create('a',{}, ['Welcome'])
    );

    $('#wrapper').append($(el));

    הגב
  7. dfgc2 בדצמבר 2009 ב 22:50

    function ControlHolder(id, control) {
    this.span = $.create("span", {"class":"xyz", "id":id}, "Group");
    this.legend = $.create("legend", {}, this.span);
    this.fieldset = $.create("fieldset",{}, this.legend);
    $(this.fieldset).append(control);
    return this.fieldset;
    }

    You _CAN_ nest elements, however what I cannot seem to do is add a function.. any suggestions?

    The following code does not work

    var myFunction = function(){ alert(1) };
    $.create("span", {
    "onclick": myFunction
    } ,"Click Me")

    הגב
  8. Basil Goldman20 בדצמבר 2009 ב 20:30

    It's work fine man, please correct your syntax. (See below…)

    var myFunction = function() { alert("OK"); }

    var obj = $.create('a', { 'onclick' : 'myFunction()' } ,['Click Me']);

    $(put_your_element_here).append(obj);

    But I think you don't need to set the "callers / functions" on elements like this sample. You have a rich and full functionality from jQuery prototype.

    Just think's

    ================================================

    Basil

    Best regards

    הגב
  9. Alex Koti21 במרץ 2010 ב 1:47

    observation: IE[s] allways require 3th argument.
    expected object in line 31:

    children = jQuery.create.apply(null, children);

    הגב
  10. Manuel26 באפריל 2010 ב 19:29

    i HATE jquery!!!!! screw this. its a pain to get the element in a var.

    function create(name,attributes,style)
    {
    var tag = document.createElement(name);

    var i;
    for(i in attributes) tag.setAttribute(i, attributes[i]);
    for(i in style) tag.style[i] = style[i];

    return tag;
    }

    הגב
  11. René Pardon9 במאי 2010 ב 10:39

    What a tiny but great thing!!

    thanks for that..

    best regards

    הגב
  12. Peter Schuebl29 בספטמבר 2010 ב 9:19

    Exactly what I was looking for.
    But than I looked a bit further and after a bit of digging in the jQuery documentation I discovered that I don't need it.

    Using jQuery out of the box functionality already provides the functionality to create multiple attributes from JSON:

    var o = $('div').attr({
    'id':'wrapper-header',
    'class':'header'
    }).html('Hello world!!!');

    הגב
  13. Mohan Ram17 בדצמבר 2010 ב 15:39

    I am using your plugin to create html elements. once i create checkbox with necessary attributes ie7 wont display checkbox

    הגב
  14. Istratov Vadim19 בינואר 2011 ב 17:56

    As Alex Koti already mentioned before this method requires to have at least 1 or 3 or more parameters; 2 parameters are not supported. You will see bogus behaviour only in IE ( object required error ).

    Thus parameters are:
    1. Element to create
    2. Attributes of this element
    3. Siblings (i.e. text for

    element or

    הגב
  15. blogs.microsoft.co.il20 באפריל 2011 ב 21:38

    Jquery create jquery plug in to create elements.. I like it 🙂

    הגב
  16. Dinesh Karki26 באפריל 2011 ב 11:53

    great tips and is very very helpful .thank's for the post.

    הגב
  17. blogs.microsoft.co.il7 במאי 2011 ב 5:32

    Jquery create jquery plug in to create elements.. Great! 🙂

    הגב
  18. blogs.microsoft.co.il20 ביוני 2011 ב 21:02

    Jquery create jquery plug in to create elements.. Tiptop 🙂

    הגב
  19. Ollie1 ביולי 2011 ב 9:21

    Great article, thank you again for wriitng.

    הגב
  20. Thinkmachine23 בדצמבר 2011 ב 3:08

    Its a great plugin and it is so much helpful. At one point I was trying to create 85 list items with images (all retrieved from database) and binding it to Un-ordered list. It dint work. But if i reduce the number of items from 85 to 80 it works fine. I would really appreciate if you could clarify me this.

    Thanks

    הגב
  21. miliodiguibne21 באוגוסט 2012 ב 13:20

    awesome…!!!

    הגב
  22. NighsofsMog26 בדצמבר 2012 ב 16:41

    שיער לגווןבאחריזמן רב של חיים ובכל נסיבות של צמיחה . חלק הארוך ביותרבחי הגבינה שלו הגדולה – עד 4 או אפילו 10 שנים , אבלעין צמות בתי השחי, הגבותוהריסים – 3-4 חודשים בלבד. הגברת היפנית הירוקו Yamaske הישן לקח 18 שנים להגיע להיקפו הגדול ביותר של להקת סיומת הרגילה של 2.6 מ ' תלתליםלתקופה – המעורב 0.35-0.4 מ"מ,ובסופו של יום הם נובעים לא כהלכה , ועדיף בשעתי הערב. במקור , שבר זקן ובית השחי צומח באופן פעיל יותר מאשרבהפסקה של הגוף.

    הגב