texto obtener modificar elementos elemento div contenido con cambiar boton atributos atributo agregar javascript jquery

javascript - obtener - ¿Cómo puedo cambiar el texto de un elemento sin cambiar sus elementos secundarios?



modificar elementos html con javascript (13)

Me gustaría actualizar el texto del elemento dinámicamente:

<div> **text to change** <someChild> text that should not change </someChild> <someChild> text that should not change </someChild> </div>

Soy nuevo en jQuery, por lo que esta tarea parece ser bastante desafiante para mí. ¿Alguien podría indicarme una función / selector para usar?

Si es posible, me gustaría hacerlo sin agregar un contenedor nuevo para el texto que necesito cambiar.


Ver en acción

Margen :

$(function() { $(''input[type=button]'').one(''click'', function() { var cache = $(''#parent'').children(); $(''#parent'').text(''Altered Text'').append(cache); }); });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parent">Some text <div>Child1</div> <div>Child2</div> <div>Child3</div> <div>Child4</div> </div> <input type="button" value="alter text" />


Aquí hay otro método: http://jsfiddle.net/qYUBp/7/

HTML

<div id="header"> **text to change** <div> text that should not change </div> <div> text that should not change </div> </div>

JQUERY

var tmp=$("#header>div").html(); $("#header").text("its thursday").append(tmp);


Creo que estás buscando .prependTo ().

http://api.jquery.com/prependTo/

También podemos seleccionar un elemento en la página e insertarlo en otro:

$ (''h2''). prependTo ($ (''. contenedor''));

Si un elemento seleccionado de esta forma se inserta en otro lugar, se moverá al destino (no clonado):

<div class="container"> <h2>Greetings</h2> <div class="inner">Hello</div> <div class="inner">Goodbye</div> </div>

Sin embargo, si hay más de un elemento objetivo, se crearán copias clonadas del elemento insertado para cada objetivo después del primero.


El problema con la respuesta de Mark es que obtienes también textnodes vacíos. Solución como complemento jQuery:

$.fn.textnodes = function () { return this.contents().filter(function (i,n) { return n.nodeType == 3 && n.textContent.trim() !== ""; }); }; $("div").textnodes()[0] = "changed text";


Esta es una vieja pregunta, pero puedes hacer una función simple como esta para hacerte la vida más fácil:

$.fn.toText = function(str) { var cache = this.children(); this.text(str).append(cache); }

Ejemplo:

<div id="my-div"> **text to change** <p> text that should not change </p> <p> text that should not change </p> </div>

Uso:

$("#my-div").toText("helloworld");


Muchas respuestas excelentes aquí, pero solo manejan un nodo de texto con hijos. En mi caso, necesitaba operar en todos los nodos de texto e ignorar html children PERO PRESERVAR EL PEDIDO.

Entonces, si tenemos un caso como este:

<div id="parent"> Some text <div>Child1</div> <div>Child2</div> and some other text <div>Child3</div> <div>Child4</div> and here we are again </div>

Podemos usar el siguiente código para modificar solo el texto Y PRESERVAR EL PEDIDO

$(''#parent'').contents().filter(function() { return this.nodeType == Node.TEXT_NODE && this.nodeValue.trim() != ''''; }).each(function() { //You can ignore the span class info I added for my particular application. $(this).replaceWith(this.nodeValue.replace(/(/w+)/g,"<span class=''IIIclassIII$1'' onclick=''_mc(this)'' onmouseover=''_mr(this);'' onmouseout=''_mt(this);''>$1X</span>")); });

<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script> <div id="parent"> Some text <div>Child1</div> <div>Child2</div> and some other text <div>Child3</div> <div>Child4</div> and here we are again </div>

Aquí está el jsfiddle de él trabajando


Para el caso específico que mencionas:

<div id="foo"> **text to change** <someChild> text that should not change </someChild> <someChild> text that should not change </someChild> </div>

... esto es muy facil:

var div = document.getElementById("foo"); div.firstChild.data = "New text";

No dices cómo quieres generalizar esto. Si, por ejemplo, quiere cambiar el texto del primer nodo de texto dentro de <div> , podría hacer algo como esto:

var child = div.firstChild; while (child) { if (child.nodeType == 3) { child.data = "New text"; break; } child = child.nextSibling; }


Respuesta simple:

$("div").contents().filter(function(){ return this.nodeType == 3; })[0].nodeValue = "The text you want to replace with"


Simplemente ajuste el texto que desea cambiar en un lapso con una clase para seleccionar.

No responde necesariamente a su pregunta que sé, pero, probablemente, una mejor práctica de codificación. Mantenga las cosas limpias y simples

<div id="header"> <span class="my-text">**text to change**</span> <div> text that should not change </div> <div> text that should not change </div> </div>

Voilà!

$(''#header .mytext'').text(''New text here'')


Mark tiene una mejor solución con jQuery , pero también puede hacer esto en JavaScript normal.

En Javascript, la propiedad childNodes le proporciona todos los nodos secundarios de un elemento, incluidos los nodos de texto.

Por lo tanto, si supiera que el texto que desea cambiar siempre será lo primero en el elemento, entonces, por ejemplo, este HTML:

<div id="your_div"> **text to change** <p> text that should not change </p> <p> text that should not change </p> </div>

Podrías hacer esto:

var your_div = document.getElementById(''your_div''); var text_to_change = your_div.childNodes[0]; text_to_change.nodeValue = ''new text'';

Por supuesto, todavía puede usar jQuery para seleccionar <div> en primer lugar (es decir, var your_div = $(''your_div'').get(0); ).


$.fn.textPreserveChildren = function(text) { return this.each(function() { return $(this).contents().filter(function() { return this.nodeType == 3; }).first().replaceWith(text); }) } setTimeout(function() { $(''.target'').textPreserveChildren(''Modified''); }, 2000);

.blue { background: #77f; } .green { background: #7f7; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="target blue">Outer text <div>Nested element</div> </div> <div class="target green">Another outer text <div>Another nested element</div> </div>


<div id="divtochange"> **text to change** <div>text that should not change</div> <div>text that should not change</div> </div>

$(document).ready(function() { $("#divtochange").contents().filter(function() { return this.nodeType == 3; }) .replaceWith("changed text"); });

Esto solo cambia el primer nodo de texto


$("div").contents().filter(function(){ return this.nodeType == 3; }).filter('':first'').text("change text");

Fuente: http://api.jquery.com/contents/

ACTUALIZACIÓN 2017 (adrach): parece que varias cosas han cambiado desde que se publicó esta publicación. Aquí hay una versión actualizada

$("div").contents().filter(function(){ return this.nodeType == 3; }).first().replaceWith("change text");