Reputation: 337
I want to change the text without change the span. I tried this one the text is changed but the span was removed.
<div class="c1"> <h2> "here" <span class="span1">X</span></h2></div>
is there any way to change the text without any change in the span content using jQuery.
Upvotes: 6
Views: 22940
Reputation: 115242
Update the nodeValue
of first textNode
.
querySelector()
- get the dom object firstChild
- get the firstNode , in this case we can get the textNodenodeValue
- updating the textNode contentdocument.querySelector('.c1 h2').firstChild.nodeValue = 'hi'
<div class="c1">
<h2>here<span class="span1">X</span></h2>
</div>
UPDATE : Or in jQuery use contents()
and 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>
Upvotes: 3
Reputation: 5897
jsFiddle : https://jsfiddle.net/CanvasCode/y6p6xzfx/
$(function () {
$span = $('h2').find('span')
$('h2').text("Hello");
$('h2').append($span);
});
Take a copy of your span, update the h2 text and then append the span back to your h2 tag.
Forgot to filter by the c1
div 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);
});
Also you don't need to store all of the elements. I was just doing this to make the code clearer to read and understand.
Upvotes: 5
Reputation: 763
You could acheive this by appending the span
to h2
element again:
var $span = $("div.c1 span.span1");
$("div.c1 h2").text("New Text");
$("div.c1 h2").append($span);
http://jsfiddle.net/6e8gw7d2/10/
Upvotes: 0