1

I am currently trying to get some data from an online json element generator, which generates random users data. I want to manipulate this data and put it in the middle of my "contacts" page.

Everything is going well, the only problem I'm facing is that I don't know how to put this div, which I creat in JS, in the middle of my page, as it appears always after the footer. I already tried to create a div in the html template and in the JS append a child to this div, but it doesn't work.

Thanks in advance.

getResultado();


function getResultado() {
    fetch("https://randomuser.me/api/")
        .then(function(response) {
            return response.json();
        }).then(function(json) {
        for (var i =0; i<json.results.length; i++) {
            console.log(json.results[i]);
            obj = json.results[i];
            document.body.appendChild(contactos(obj));
        }
    });
}
let jsonDiv = document.getElementById("json");
function contactos(info){
    let contactosElement = document.createElement("div");
    contactosElement.classList.add("contactos");

    let contactoElement = document.createElement("div");
    contactoElement.classList.add("contacto");

    let tituloElement = document.createElement("h3");
    tituloElement.innerText = "Geral";

    let nomeElement = document.createElement("p");
    nomeElement.innerText = info.name.first;

    let mailElement = document.createElement("p");
    mailElement.innerText = info.email;


    jsonDiv.appendChild(contactosElement);

    contactosElement.appendChild(contactoElement);
    contactoElement.appendChild(tituloElement);
    contactoElement.appendChild(nomeElement);
    contactoElement.appendChild(mailElement);

    return contactosElement;
}
<!DOCTYPE html>
<html lang="en">
<head>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Fahkwang&display=swap" rel="stylesheet">
    <meta charset="UTF-8">
    <title>Contactos</title>
    <link rel="stylesheet" type="text/css" href="CSS/stylesheet.css">
    <link rel="stylesheet" type="text/css" href="CSS/contactos.css">
</head>
<body>
<header>
    <div class="header">
        <div class="logo"><a href="home.html"><img width="100" height="100" src="imagens/qf.png" alt="logo"></a></div>
        <div class="barras" onclick="anim(this); abrir()">
            <div id="barra1"></div>
            <div id="barra2"></div>
            <div id="barra3"></div>
        </div>
        <div class="links">
            <a href="cartaz.html">CARTAZ</a>
            <a href="historia.html">HISTÓRIA</a>
            <a href="contactos.html">VOLUNTARIA-TE</a><a
                href="loja.html">LOJA</a>
        </div>
    </div>
</header>
<main>
    <div class="titulo"><h1>Voluntaria-te</h1></div>
    <form>
        <label for="pnome" class="titulo">Primeiro Nome</label>
        <input type="text" id="pnome" name="pnome" placeholder="O seu primeiro nome...">

        <label for="unome" class="titulo">Apelido</label>
        <input type="text" id="unome" name="unome" placeholder="O seu ultimo nome...">

        <label for="telemovel" class="titulo">Telemóvel:</label>
        <input type="tel" id="telemovel" name="usuario_telemovel" placeholder="O seu número de telemóvel...">

        <label for="profissão" class="titulo">Profissão:</label>
        <input type="text" id="profissão" name="usuario_profissão" placeholder="A sua profissão...">

        <label for="país" class="titulo">País de Nascimento</label>
        <select id="país" name="país">
            <option value="portugal">Portugal</option>
            <option value="espanha">Espanha</option>
            <option value="frança">França</option>
        </select>

        <label for="data" class="titulo">Data de Nascimento</label>
        <input type="date" id="data" name="data">

        <label for="carta" class="titulo">Carta de Motivação:</label>
        <textarea id="carta" placeholder="Qual a importância desta experiência para si?"></textarea>

        <input type="submit" value="Submeter">
    </form>


    <div id="json"></div>

</main>
<footer>
    <div id="redes">
        <a href="https://www.facebook.com/queimadasfitascoimbra/" target="_blank"><img width="40" height="40"
                                                                                       src="imagens/fb.png"
                                                                                       alt="fb"></a>
        <a href="https://www.instagram.com/queimadasfitascoimbra/" target="_blank"><img width="40" height="40"
                                                                                        src="imagens/insta.png"
                                                                                        alt="insta"></a>
        <a href="https://twitter.com/queimacoimbra" target="_blank"><img width="40" height="40" src="imagens/tt.png"
                                                                         alt="tt"></a>
    </div>
    <div>
        <address>
            E-mail: queimadasfitascoimbra.pt <br>
            Morada:Rua Padre António Vieira, 1 3000-315 Coimbra <br>
        </address>
    </div>
</footer>
<script src="JS/json.js"></script>
<script src="JS/menu.js"></script>
</body>
</html>
  • Your approach with appending a child to another div is very close to a working solution. Using e.g. jQuery you can use `insertAfter` to accomplish it with minimal code: https://api.jquery.com/insertAfter/ – JSRB Dec 22 '19 at 15:38
  • the problem is that i can only use pure js :/ – Jorge Santos Dec 22 '19 at 15:40
  • Why? Just insert jQuery CDN into your template as script tag and you are good to go. – JSRB Dec 22 '19 at 15:41
  • it´s for a university work, jquery is not allowed – Jorge Santos Dec 22 '19 at 15:43
  • maybe this helps https://stackoverflow.com/questions/4793604/how-to-insert-an-element-after-another-element-in-javascript-without-using-a-lib – JSRB Dec 22 '19 at 15:44

1 Answers1

2

The issue is that you're doing:

document.body.appendChild(contactos(obj));

This will literally append a new child to the end of the body element. Since your footer is already at the end of body, your new elements will come after the footer.

What you should really do is create a unique container on your page before the footer and give it an ID, say contacts, and append to that element:

<body>
  <header>Your header stuff here</header>
  <main>
    ...
    <!-- Append to this -->
    <section id="contacts"></section>
    ...
  </main>
  <footer>This is your footer</footer>
</body>
// outside the loop
const contacts = document.getElementById('contacts');
...
// in your loop
contacts.appendChild(contactos(obj));

But it seems you already have such a placeholder div with an ID of json. The issue remains, however, since you then do document.body.appendChild(contactos(obj)), and that effectively puts everything at the end of the body.

I would approach the problem like this:

  1. The contactos function should only worry about returning your contactos element. I would actually avoid naming these two the same thing, as that gets a little confusing. Maybe call the element contactosElement.

  2. Get a reference to the json div.

  3. Append the result of #1 to the json div in your loop, instead of doing document.body.appendChild(contactos(obj)).

  • I am sorry, i think that´s exactly what i did, i created a div called "json" in my html, then, in the js i wrote: let json = document.getElementById("json"); json.appendChild(contactos); isn´t it, what you are saying? – Jorge Santos Dec 22 '19 at 15:56
  • Edited to clarify the issue. You're right that you have a `json` div. However, you are still ultimately appending the result of the `contactos` function to the body. – Aleksandr Hovhannisyan Dec 22 '19 at 16:05
  • Sorry, in fact i was naming the contactosElement as contactos, which is the same name as in the function, i already changed it to contactos element. Then, i inserted my let json=document.getElementByID outside the loop as you sugested but it didnt work. but there is one thing i dont understand in your reply, which is the fact that i am not doing this: "document.body.appendChild(contactos(obj))" i am actualy doing this: " contactos.appendChild(contacto);" – Jorge Santos Dec 22 '19 at 16:54
  • i actually don´t even know where did you find this: "document.body.appendChild(contactos(obj))." – Jorge Santos Dec 22 '19 at 16:56
  • It's in `getResultado`. – Aleksandr Hovhannisyan Dec 22 '19 at 17:00
  • (Anyway i edited it to the new version, where the elements are named properly and the let json declaration is outside the loop – Jorge Santos Dec 22 '19 at 17:02
  • OOOOOOH, now i understood, i used this piece of code from a Exercise i did in the classes, i would never find it, let me see if it solves it – Jorge Santos Dec 22 '19 at 17:04