Change the text in <h2> without changing the span of the same h2 tag

I want to change the text without changing the range. I tried this text, but the text was deleted.

 <div class="c1"> <h2> "here" <span class="span1">X</span></h2></div>

is there any way to change the text without any changes to the contents of the range using jQuery.

+4
source share
4 answers

jsFiddle: https://jsfiddle.net/CanvasCode/y6p6xzfx/

$(function () {
    $span = $('h2').find('span')
    $('h2').text("Hello");
    $('h2').append($span);
});

Take a copy of your range, refresh the h2 text, and then add the span back to the h2 tag.


I forgot the filter using the c1div class . here is the updated code

jsFiddle https://jsfiddle.net/CanvasCode/y6p6xzfx/1/

$(function () {
    $div = $('.c1');
    $h2 = $div.find('h2');
    $span = $h2.find('span')
    $h2.text("Hello");
    $h2.append($span);
});

. , .

+4

nodeValue textNode.

document.querySelector('.c1 h2').firstChild.nodeValue = 'hi'
<div class="c1">
  <h2>here<span class="span1">X</span></h2>
</div>
Hide result

UPDATE: jQuery contents() replaceWith()

$('.c1 h2').contents().first().replaceWith('hi');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="c1">
  <h2>here<span class="span1">X</span></h2>
</div>
Hide result
+3

You can achieve this by adding the element spanto h2it again:

var $span = $("div.c1 span.span1");
$("div.c1 h2").text("New Text");
$("div.c1 h2").append($span);

http://jsfiddle.net/6e8gw7d2/10/

0
source

Solution: $ ('. Span1'). text ('ABC');

-3
source

Source: https://habr.com/ru/post/1613797/


All Articles