Add Divs to a given position with Javascript

Asked

Viewed 25 times

0

Hello! I am trying to implement Divs on a website when the user clicks on an image with a + .
These Divs themselves are a form of transition to other pages, however when added by javascript their function stops working.

<p id="adicionar_mais1"><img src="Imagens/Mais.jpg" onclick="Adicionar1()" id="Mais"></p>

function Adicionar1() {
    var primeirasoma = " <div onclick='location.href='Artigo19.html''><p><img src='Fotografias/foto86.jpg'></p><p class='topico space'><b>Titulo</b> 12.02.2020</p><p class='nomeart'>SEGUNDOTITULO</p><p class='descri'>TEXTO TEXTO</p></div>";

          ;
  document.getElementById("adicionar_mais1").innerHTML = 
   primeirasoma;
}
</script>

I think the problem is that I had to change the "" to '' and that changed the location href, but I don’t know how else to add this kind of elements to the page.

Does anyone know what I should change in my code to make it work, or if possible another easier method if there is, since I will have to add several Ivs at once.

Thank you!!

1 answer

0


Dude if you want to do this just with javascript I would do so...

function Adicionar1() {

if (!document.querySelector('.topico')) {
    document.querySelector('#Mais').remove();

    //Element <div>
    var div = document.createElement('div');
    div.setAttribute('onclick', "location.href='Artigo19.html'");

    //Element <p>
    var p1 = document.createElement('p');

    //Element <img>
    var img = document.createElement('img');
    img.setAttribute('src', 'Fotografias/foto86.jpg');

    p1.appendChild(img);

    //Element <p>
    var p2 = document.createElement('p');
    p2.setAttribute('class', 'topico space');
    //Element <b>
    var b = document.createElement('b');
    var textB = document.createTextNode('Título');
    b.appendChild(textB);
    p2.appendChild(b);
    //Element <h4>
    var h4 = document.createElement('h4');
    var textH4 = document.createTextNode('12.02.2020');
    h4.appendChild(textH4);
    p2.appendChild(h4);
    //Element <p>
    var p3 = document.createElement('p');
    p3.setAttribute('class', 'nomeart');
    var textP3 = document.createTextNode("SEGUNDO TITULO");
    p3.appendChild(textP3)

    var p4 = document.createElement('p');
    p3.setAttribute('class', 'descri');
    var textP4 = document.createTextNode("SEGUNDO TITULO");
    p4.appendChild(textP4)

    //Adicionar Todos os elementos na div

    var htmlElement = document.getElementById("adicionar_mais1");

    div.appendChild(p1);
    div.appendChild(p2);
    div.appendChild(p3);
    div.appendChild(p4);

    htmlElement.appendChild(div);
}}

But I recommend that you use CSS together with JS. The code will be more readable.

Browser other questions tagged

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