GoldenNewby
GoldenNewby

Reputation: 4452

Easy way of manipulating the DOM in Javascript

I am curious if there is an existing javascript framework that allows you to more easily create DOM in javascript.

Currently, I am changing the DOM like this:

var header_field = document.createElement('h1');
header_field.className = "header";
header_field.innerHTML = "This is the header";
parent_dom.appendChild(header_field);

... as an example.

Is there a framework that will say, interpret a javascript object, and manipulate the DOM based on that? I kind of envision something like:

jQuery.createDOM(
  [
    { element : 'h2', text : "This is the header", class : "header" }
  ]
);

... or something of that style.

For complex Ajax-Driven sites, I find myself typing a lot of repetitive code in order to create otherwise simple HTML. So, is there a framework out there that makes the process of manipulating the DOM in javascript considerably easier? Does jQuery already offer this and I just haven't heard of it?

Upvotes: 0

Views: 2684

Answers (5)

gilly3
gilly3

Reputation: 91637

Writing repetitive code is completely avoidable. Whenever you find you've written the same code more than once or twice, encapsulate it in a function.

function h1(text) {
    return $("<h1>").addClass("header").text(text);
}

Take it a level deeper:

function el(name, className, text) {
    className = className || "";
    text = text || "";
    return $("<" + name + ">").addClass(className).text(text + "");
}
function h1 (text) {
    return el("h1", "header", text);
}

Keep going with it and you can do something like create an entire article by calling something like this:

function article(titleText, author, postDate, content) {
    return el("div", "article").append(
        h1(titleText),
        authorEl(author),
        dateEl(postDate),
        content);
}
$("#articles").append(article("some title", authors.Joe, new Date(), someContent));

Edit: If that's more than what you're looking for, jQuery does make it easier to create elements. For example, you could create a close button for every popup dialog on your page with something like this:

$("<div>").addClass("close").text("\xd7").prependTo(".dialog").click(function () {
    $(this).closest(".dialog").hide();
});

Similarly, add styles using .css({ backgroundColor: "#fff", border: "1px solid blue" }), add attributes using .attr({ type: "checkbox" }), properties: .prop({ checked: true }). The list goes on.

Upvotes: 4

Nathan
Nathan

Reputation: 12010

Just create new elements with a function like this and give them an ID if you want to reference to it later:

function newElement(tag,class,text,id) {
if(!id) id='';
if(!class) class='';
return $('<' + tag + '>').addClass(class).html(text).attr('id',id);
}

Then you can do this:

newElement("h1","class-name-here","Hello, this is a header","id-here");

If you want to append it to the document, just do this (you don't even need to variable if you don't want):

var ele = newElement("h1","class-name-here","Hello, this is a header","id-here");
$('body').append(ele);

Upvotes: 0

Madbreaks
Madbreaks

Reputation: 19549

In jQuery:

$('<h2 />').addClass('header').html('This is the header');

EDIT

Add this to your document and save a reference to it with, e.g.

var myHeader = $('<h2 />').addClass('header').html('This is the header');
$('body').append(myHeader);

Cheers

Upvotes: 1

Kevin B
Kevin B

Reputation: 95063

You can abstract frequently used dom manipulation behind functions pretty easily:

function buildEntry(obj) {
    return [
        "<li",
        ( obj.class ? " " + obj.class : ""),
        ">",
        ( obj.header ? "<h2>" + obj.header + "</h2>" : "" ),
        ( obj.subheader ? "<h3>" + obj.subheader + "</h3>" : "" ),
        ( obj.content ? "<p>" + obj.content + "</p>" : "" ),
        "</li>"
    ].join("");
}
$.getJSON(url,data,function(){
    var strOutput = "";
    $.each(data,function(i,obj){
        strOutput += buildEntry(obj);
    });
    $("ul").html(strOutput);
});

Upvotes: 1

Guumaster
Guumaster

Reputation: 389

If you don't want to use jQuery, just do something like this:

 var h2 = '<h2 class="header">This is the header</h2>';
 parent_dom.innerHTML = h2; // use += to append

readable and quick to write.

If you are looking for a template system. Look at Underscore's template() function.

Upvotes: 0

Related Questions