Sumanth Jois
Sumanth Jois

Reputation: 3234

JavaScript not able to replace text with new text

I am trying to convert selected text's font with help of AngularJs and jQuery. This is my code. Everything is working fine but i am not able to change the text with a new text.

This is my code:

   var app = angular.module('myApp', []);
   app.controller('editor', function($scope) {
     $scope.color = "black";
     $scope.selectedText = "";
     $scope.changeFont = function() {
       if ($scope.selectedText != "") {
         var changedText = "<span style='font-size:" + $scope.kys_selected_font + "px' >" + $scope.selectedText + "</span>";
         alert($scope.selectedText + $scope.kys_selected_font + "      " + changedText);
         document.getElementById("#content").innerHTML.replace($scope.selectedText, changedText);
       } else {
         $("#content").append("<span  id='one' style='font-size:" + $scope.kys_selected_font + "px' > this is some text </span>");
         $("#one").focus();
       }
     };
     $("#content").mouseup(function() {
       $scope.selectedText = window.getSelection();

     });
   });

Upvotes: 2

Views: 93

Answers (1)

CupawnTae
CupawnTae

Reputation: 14580

innerHTML.replace(...) returns a new string, rather than modifying the existing one, so your replacement won't modify the element.

You need to actually update the property:

var el = document.getElementById("content");
el.innerHTML = el.innerHTML.replace($scope.selectedText, changedText);

(also note # removed from element ID as per @IvanSivak's comment)

Upvotes: 1

Related Questions