0

Replace an element name in a string fails. replace() doesn't seem working.

var a = 1;

function generateDiv() { 
    a++;
    var firstDiv = $(".firstDiv").html();
    firstDiv.replace("fileName1", "fileName" + a);  
    $('#mainDiv').append(firstDiv);
}
3
  • can you show the html as well? Commented Apr 22, 2016 at 11:20
  • 2
    firstDiv = firstDiv.replace("fileName1","fileName"+a) Commented Apr 22, 2016 at 11:20
  • 1
    Note that instead of amending the HTML string (which could lead to unexpected changes if you have the name repeated elsewhere in the code) you could just clone() the elements and change the name property of the required element. Commented Apr 22, 2016 at 11:22

2 Answers 2

1

You need to update the variable value, replace() will return the new string and it will not update the variable.

var a = 1;

function generateDiv() {
  a++;
  var firstDiv = $(".firstDiv").html();
  firstDiv = firstDiv.replace("fileName1", "fileName" + a); // update the variable with returned value
  // or do it in single line
  // var firstDiv = $(".firstDiv").html().replace("fileName1", "fileName" + a);  
  $('#mainDiv').append(firstDiv);
}

Sign up to request clarification or add additional context in comments.

Comments

1

Replace returns replaced string, it is not replaces variable... so please do it like

firstDiv = firstDiv.replace("fileName1", "fileName" + a);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.