Si8
Si8

Reputation: 9225

How to search by line and replace content for that line

Fiddle

$(".my-item").each(function() {
    var lines = $(this).text().split("\n");
  var k = "";

  $.each(lines, function(n, elem) {
    if (elem.trim().length > 0) {
      if (elem.indexOf('my info1 & test') !== -1) {
        alert("in here");
        debugger;
        elem.replace('959', '600');
        alert(elem);
      }
    }
  });
});

As I am searching by line and the condition is met, I would like to replace the text in the DOM but it's not working...

Any help, please...

Upvotes: 1

Views: 39

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Working fiddle.

You could store the lines in an array variable (result in my example) then join them at the end with the new line using join() and finally replace them in the DOM :

$(this).text(result.join("\n"));

$(".my-item").each(function() {
  var lines = $(this).text().split("\n");
  var result = [];

  $.each(lines, function(n, elem) {
    if (elem.trim().length > 0) {
      if (elem.indexOf('my info1 & test') !== -1) {
        elem = elem.replace('959', '600');
      }
    }

    result.push(elem);
  });

  $(this).text(result.join("\n"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<dd class="my-item" style="height: 44px;">
  my info1 &amp; test 959 my info2 &amp; test 1200 my info3 &amp; test 450 my info4 &amp; test 908
</dd>

Upvotes: 2

Related Questions