1

I am making bunch of elements that look like the same

I have

<div id="e1" class="e1">

        <div class=box>
            <div class='b1'></div>
            <div class='b2'></div>
            <div class='b3'></div>
            <div class='b4'></div>
        </div> 

    <div class='e11'></div>     
    <div class='e12'></div>     
    <div class='e13'></div>     
    <div class='e14'></div>     
    <div class='e15'></div>                                     
        ...more elements
<div>


<div id="e2" class="e2">

        <div class=box>
            <div class='b1'></div>
            <div class='b2'></div>
            <div class='b3'></div>
            <div class='b4'></div>
        </div> 

    <div class='e11'></div>     
    <div class='e12'></div>     
    <div class='e13'></div>     
    <div class='e14'></div>     
    <div class='e15'></div>                                         
        ...more elements
<div>

They are almost the same and I have several e3 and e4 div...

MY question is if there are anyways to reduce the codes and create them in js with an object (or better approach).

Would anyone gives me a hint? Thanks a lot!

FlyingCat
  • 14,036
  • 36
  • 119
  • 198
  • what is your objective? Reducing code can't be your only reason? – Sebas Mar 22 '13 at 22:36
  • 2
    Just as a note, you shouldn't re-use "id" values on multiple elements ("box"). You can use "class" instead. – Pointy Mar 22 '13 at 22:36
  • 1
    You're looking for _HTML templating,_ server-side or client side. Do some research with that term. – Matt Ball Mar 22 '13 at 22:36
  • @Sebas yes Sebas, I am trying to reduce the cumbersome of the same type of elements. for Pointy, Sorry it was a typo. – FlyingCat Mar 22 '13 at 22:39

1 Answers1

1

jsFiddle Demo

You are going to need to get some iteration parameters, and then make a function which iterates based on those parameters to create these html elements. The primary way do create an html element is

document.createElement("tagname");

and then you are going to need to append them in the order you wish. Once they are done, you can append them to an element on the screen. Avoid appending inside of a loop. Even if you create a lot of elements, they will render quickly if they are only appended onto the screen once instead of each time an element is created.

Here is a simple example:

<div id="contentZone"></div>
<script>
 var c = document.getElementById("contentZone");
 var content = document.createElement("div");
 for( var i = 0; i < 3; i++ ){
  var d = document.createElement("div");
  d.innerHTML = i + ") Hello :D";
  content.appendChild(d);
 }
 c.appendChild(content);
</script>
Travis J
  • 81,153
  • 41
  • 202
  • 273