kalles
kalles

Reputation: 337

change the text in the <h2> without change the span the same h2 tag

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

Answers (4)

Pranav C Balan
Pranav C Balan

Reputation: 115242

Update the nodeValue of first textNode.

  1. querySelector() - get the dom object
  2. firstChild - get the firstNode , in this case we can get the textNode
  3. nodeValue - updating the textNode content

document.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

Canvas
Canvas

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

Fayyaz Naqvi
Fayyaz Naqvi

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

Kalyan
Kalyan

Reputation: 1

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

Upvotes: -3

Related Questions