You can insert new HTML with Pure.js

Asked

Viewed 49 times

2

I’m looking to use the Pure.js framework to create a post via json.

I found it on the Stack platform in English this topic, which is what I want to do, only that there’s a problem, I’m not being able to do the example of the second person who answered below.

Arturo Hernandez;

In your example, your HTML template should look like this:

<ul>
  <li>
    <img src="/img/pappo.gif" />
    <h1>marte</h1>
    <p><a href="http:://www.sito.it>guille</a></p>
  </li>
</ul>

and a json likes it:

{
   "mylist":{
      "listone": 
          {"img" : "/img/pippo1.gif" ,
           "text1" : "pluto1",
           "text2" : "topolino1",
           "link" : "http://www.sito1.it"       
           },
      "listtwo":
          {"img" : "/img/pippo2.gif" ,
           "text1" : "pluto2",
           "text2" : "topolino2",
           "link" : "http://www.sito2.it"       
          }
   }
}

and the end should be like this:

<ul>
  <li>
    <img src="/img/pippo1.gif" />
    <h1>pluto1</h1>
    <p><a href="http:://www.sito1.it>topolino1</a></p>
  </li>
  <li>
    <img src="/img/pippo2.gif" />
    <h1>pluto2</h1>
    <p><a href="http:://www.sito2.it>topolino2</a></p>
  </li>
</ul>

The first I get to do good, now that second of two, I don’t get.

What the javascript code would look like?

1 answer

1


If you have a list of objects it is easier, so you can go through the list and associate the values of each object to the html injection you want to do. By the way, you can do html injection without any framework.

An example of object list:

    { 
      listaObj : [
        {
          nome : "Testador",
          idade : 25,
          sexo : "M"
        },{
          nome : "Testadora",
          idade : 22,
          sexo : "F"
        }
     ]
   }

This way you go through the list looking at objects more dynamically only using their attributes and you can do the html injection. Here is an example using the list of objects above.

var divCentral = document.getElementById("central");
for(var i = 0; i < listaObj.length; i++){
  var divNome = document.createElement("div")
  divNome.innerHTML = listaObj[i].nome
  divCentral.appendChild(divNome)
}

This way it is indifferent the size of the list of its objects, the code will always work.

:)

  • Could you do the example above in jsfiddle? , there is only the demo with the "name".

  • 1

    Opa, sorry for the delay! Yes I can, today I provide you.

  • 1

    @Matheuscalixto Follow the example in fiddle, it is very basic but it is possible to base on it, make a test increasing the amount of objects to see how it works. https://jsfiddle.net/tetbdkpe/

  • Thanks Luan I’ll take a look;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.