Search code examples
javascriptjqueryhtmlglyphicons

.text() affects html elements inside h1


I have the following markup:

<h1>A text <span class="createTask glyphicon glyphicon-plus"></span></h1>

What I want to do is when I double click an h1 to change its text. To do this I wrote the following code inside a document ready function

$("h1").on("dblclick",function(){
   var newTitle = prompt("Enter a new title");
  if(newTitle){
     $(this).text(newTitle);
  }

})

However this code instead of just changing the text of the h1 it removes the glyphicon span. Any Ideas why? Also note that I cannot change the markup.


Solution

  • Using $(this).text() (.html() is the correct syntax), you are changing the entire h1 content, including the glyph inside it.

    If you want to keep the glyph (with the span), seperate them from the h1 like so:

    <h1>A text </h1><span class="createTask glyphicon glyphicon-plus"></span>
    

    Or, as you requested - without changing the markup:

    $(this).html(newTitle + "<span class='createTask glyphicon glyphicon-plus'>");