What javascript function do I use to extract an HTML block from one place and insert it into another one on the same page

0

Next I'm working on moodle and 90% of the html is generated via backend, I need to change a <h1 id='courseheader')>Title</h1> of place via javascript since I do not have access to this element, the idea was to remove it from where it is to throw it inside a container that I have on the same page.

What javascript / JQuery function can I use for this?

I searched google but could not express the question in such a clear way that it could return me answers.

I hope that here is clear the doubt, anything edited. Thank you.

Example:

<h1 id='courseheader')>Title</h1>

<div class="container"> Quero retirar o h1 ali de cima e colocá-lo aqui dentro</div>

Note: I could even create a new h1 inside the container via JS but would like to take advantage of what it already has.

Obs2.: I forgot to mention that I want this h1 together with the other elements inside the container and that it stays inside the h1 tag ...

    
asked by anonymous 10.03.2016 / 14:17

2 answers

2

You can use the code below as an example, it:

  • Capture the desired h1 element through ID
  • Capture% element of% through container
  • Adds a new clone element of className to the textContent of the container through the h1
  • Note : So that there was no line break in the container, it was necessary to add the property cloneNode(true)

    //Recuperando elemento H1 
    var h1Element = document.getElementById("courseheader");
    
    //Recuperando elemento container
    var containerElement = document.getElementsByClassName('container')[0];
    
    //Adicionando conteúdo do h1 ao container
    containerElement.appendChild(h1Element.cloneNode(true));
    h1{
      display: inline;
     }
    <h1 id='courseheader'>Title</h1>
    
    <div class="container"> Quero retirar o h1 ali de cima e colocá-lo aqui dentro</div>
        
    10.03.2016 / 14:58
    2

    Using jQuery , you have several ways to do this. I do not know if it's the most performative or the most elegant, but it solves the problem. See:

    var _h1 = $('#courseheader').html();
    
    var _container = $('.container');
    
    setTimeout(function(){
      _container.append(' ' + _h1);  
    }, 2000);
      
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h1id='courseheader'>Title</h1><divclass="container"> Quero retirar o h1 ali de cima e colocá-lo aqui dentro</div>

    setTimeout is a perfumery, just to see you working.

    EDIT

    I purposely deleted the contents of div because I thought that was what you wanted. I have edited the code to agree with your comment

        
    10.03.2016 / 14:53