How to append text only once in a loop

How to append text next to each matched link?

for (var i = 0; i < author.length; i++) {
  var adminID = author[i]["href"].match(/\/users\/(\d+)/g);
  for (var j = 0; j < userID.length; j++) {
    if (adminID == userID[j]) {
      $(`a[href*="${userID[j]}"]`).append('<span>text</span>');
    }
  }
}
728x90

2 Answers How to append text only once in a loop

Ad a flag to state it has been appended

for (var i = 0; i < author.length; i++) {
  var adminID = author[i]["href"].match(/\/users\/(\d+)/g);
  var appended = false;
  for (var j = 0; j < userID.length; j++) {
    if (adminID == userID[j] && !appended) {
      appended = true;
      $(`a[href*="${userID[j]}"]`).append('<span>text</span>');
    }
  }
}

6 days ago

Just break afterwards:

for (var i = 0; i < author.length; i++) {
  var adminID = author[i]["href"].match(/\/users\/(\d+)/g);
  for (var j = 0; j < userID.length; j++) {
    if (adminID == userID[j]) {
      $(`a[href*="${userID[j]}"]`).append('<span>text</span>');
      break;
    }
  }
}

6 days ago