Error [object Text] when trying to put value in an input type text

0

A doubt maybe basic, that I thought I'd know how to solve and I'm going crazy:

I want to recover a text that a div contains inside, save it in a variable and put it as a value in an input type text.

When I try to do this, the text that appears inside the input type text is: [object Text].

function editaCmnt(e){
    var elemento = e.target;
    elementoHijo = elemento.previousSibling;

    //Aquí recupera el div que contiene texto en su interior
    divCmts = elementoHijo.previousSibling;

    //Aquí recupera el texto
    comentario = divCmts.firstChild;

    divCmts.style.display = "none";

    //Se crea el input
    inputAñadido = document.createElement("input");

    //Se añade como valor, el texto recuperado de dentro del div
    inputAñadido.setAttribute("value", comentario)

    //Se muestra el input (en teoria con el valor "comentario")
    elemento.before(inputAñadido);
}

The text I want to recover contains $ registration ['Comment']:

"<div class='contComentarios'>
        <div class='creadorFecha'>
            <div> Creado por: <strong>". $registro2['Nombre'] ."</strong></div>
            <div>". $registro['Fecha'] ."</div>
        </div>

        <div class='comentario'>". $registro['Comentario'] ."</div>

    <div class='modificaCmnt'>
        Editar
    </div>

    <div id=".$registro['Tema']." class='borrarTema borraCmnt'>
        <div id=". $registro['IdComentario'] ." class='borraCmnt' value='Borrar comentario'>Borrar comentario</div>
    </div>

</div>";
    
asked by Mario G. Lucas 10.11.2018 в 16:50
source

1 answer

1
//Aquí recupera el texto
    comentario = divCmts.firstChild;

Here you are getting the complete element, assuming as it says your question that it is a div with text you need to access the property of the innerHTML to obtain the text it contains:

//Aquí recupera el texto
    comentario = divCmts.firstChild.innerHTML;

The problem of using innerHTML is that it includes EVERYTHING that is inside your element, for example if your <div> has nested a <input> this will appear within the innerHTML . You can use the .innerText property but this only works on block content elements (tags you have to open and close as <div> , <button> , <span> , etc)

    
answered by 10.11.2018 / 17:19
source