jquery change div text

Jquery

Jquery Problem Overview


'<div id="'+div_id+'" class="widget" style="height:60px;width:110px">\n\
            <div class="widget-head ui-widget-header" style="cursor:move;height:20px;width:130px">'+
         '<span id="'+span_id+'" style="float:right; cursor:pointer" class="dialog_link ui-icon ui-icon-newwin ui-icon-pencil"></span>'  +
          dialog_title+'</div></div>

I have a div constructed using the above string. After some processing..I have to change the dialog_title in the above div. I am trying to do it with the following code

$('#'+div_id+' .widget-head').text("new dialog title");

While this changes the dialog title..it removes the span element which is used to open a dialog box.

I tried to the replaceWith method with a string with new dialog title..but that shows NaN for title and the span though visible cant be clicked(are events disabled?)

How do I change the text without losing the span and ability to click it.

Thanks in advance.

Jquery Solutions


Solution 1 - Jquery

Put the title in its own span.

<span id="dialog_title_span">'+dialog_title+'</span>

$('#dialog_title_span').text("new dialog title");

Solution 2 - Jquery

I think this will do:

$('#'+div_id+' .widget-head > span').text("new dialog title");

Solution 3 - Jquery

best and simple way is to put title inside a span and replace then.

'<div id="'+div_id+'" class="widget" style="height:60px;width:110px">\n\
        <div class="widget-head ui-widget-header" 
                style="cursor:move;height:20px;width:130px">'+
     '<span id="'+span_id+'" style="float:right; cursor:pointer" 
            class="dialog_link ui-icon ui-icon-newwin ui-icon-pencil"></span>' +
      '<span id="spTitle">'+
      dialog_title+ '</span>'
 '</div></div>

now you can simply use this:

$('#'+div_id+' .widget-head sp#spTitle').text("new dialog title");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuruView Question on Stackoverflow
Solution 1 - JquerygubView Answer on Stackoverflow
Solution 2 - JqueryMartin ThurauView Answer on Stackoverflow
Solution 3 - JqueryTheVillageIdiotView Answer on Stackoverflow