Yasser Shaikh
Yasser Shaikh

Reputation: 47774

How to change only text inside a div which has other divs

I have html below. What I want to do depends on some conditions. I want to keep changing the text which is Sometitle.

<div id="header">
    Sometitle
    <div>
        <div>
            aa
        </div>
        <div>
            bb
        </div>
    </div>
</div>

I tried using Jquery below but it removes the other divs also.

$("#header").text("Its a thrusday today !");

How do I get this done? I cannot modify this HTML in any case. I just have to use jquery and get this thing done.

Here is a jsfiddle I created : http://jsfiddle.net/qYUBp/

Upvotes: 5

Views: 5282

Answers (5)

Nandakumar V
Nandakumar V

Reputation: 4615

can you check this

headerClone = $("#header").clone();
$(headerClone).find('div').remove();
var currentText = $(headerClone).html().replace(/(\r\n|\n|\r|\t)/gm,"");

newHtml = $("#header").html().replace(currentText,"Gotcha");
$("#header").html(newHtml);

JSFIDDLE

Upvotes: 0

Kyle Weller
Kyle Weller

Reputation: 2623

That text Sometitle is an orphan node, you are going to want to wrap an element around it to properly manipulate it

<div id="header">
    <span>Sometitle</span>
    <div>
        <div>
            aa
        </div>
        <div>
            bb
        </div>
    </div>
</div>

EDIT

But since you regrettably cannot change the html, you could do as the solution suggests in the other post. They had a typo that I corrected here:

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

check your updated JsFiddle

Upvotes: 3

Ravi Verma
Ravi Verma

Reputation: 225

for this case only, when rendering to browser

var new_s = "Its a thrusday today !";
var s = $("#header").children(":first").html();
$("#header").text(new_s+"<div>"+s+"</div>");

Upvotes: 0

arjuncc
arjuncc

Reputation: 3287

If you dont want it in a single line.

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

jsfiddle

Upvotes: 3

ap.singh
ap.singh

Reputation: 1160

try this

$("#header").html($("#header").html().replace("Sometitle","Its a thrusday today !"));

Upvotes: 0

Related Questions