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

I have html below. What I want to do depends on some conditions. I want to save the text Sometitle.

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

I tried using jQuery below, but it removes other divs as well.

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

How should I do it? I cannot change this HTML code anyway. I just need to use jquery and do this.

Here is the generated jsfiddle: http://jsfiddle.net/qYUBp/

+5
source share
5 answers

If you do not want it on one line.

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

jsfiddle

+3
source

This text Sometitleis an orphan node, you will need to wrap an element around it in order to properly manipulate it.

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

EDIT

, , html, , . , :

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

JsFiddle

+3

try it

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

for this case only when rendering to the browser

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

can check it out

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

0
source

All Articles