How can I create an element in the DOM from a php echo


Good, no matter how many laps I give an action. The case is that through ajax I call a php file that prints an html tag with echo. The problem comes when you want to handle that label (to which I have put a class) because, I presume, that is because it does not exist in the DOM.

How can I create the element in the DOM from php so I can access the element from javascript?

Here is the example that simplifies the project I am working on. A h2 in which clicking, the response of php appears. But when you click on the created paragraph, you do not recognize the class.


$btn.on('click', function() {
        url: 'prueba.php',
        success: function(response) {

$p.on('click', function() {
    <meta charset="UTF-8">
    <h1 class="titulo">Prueba</h1>
    <p>Esto es una prueba</p>
    <h2 class="click" style="cursor:pointer">Click aqui para enseñar contenido php</h2>
    <p class="contenido"></p>


    echo '<p class="parrafo">Hola mundo</p>';

Also try with this php code using the DOMDocument class

    $doc=new DOMDocument();
    $doc->loadHTML('<p class="parrafo">Hola mundo</p>');
    echo $doc->saveHTML();

Also I have also tried without ajax, loading an html file from javascript with .load (), but I can not find the way.

asked by asantana o 03.08.2017 в 18:40

1 answer


If I remember correctly, JS can update the DOM and manipulate it, but can not reload everything again (I'm not 100% sure of this), unless you reload the whole page, but obviously you do not want that , since that is why you are using AJAX . What you should do, instead of trying to update the DOM , is to use the delegation of events.

What the delegation of events refers to is to capture an event that is generated in some element that already exists in the DOM (usually an element that contains more elements) and indicate that we want to verify that this event was generated in a specific element.

I give you an example so you can take the idea and apply it anywhere else.

$(document).on('click', '.parrafo', function() {

In this example, we are monitoring the document for any event click , but we are indicating that event click must come from some element within document that matches the class .parrafo .

P.D. Just keep in mind that, in this case, the function works for all p that match that class, and you can always use $(this) to refer to the object you clicked.

answered by 03.08.2017 / 18:56