0

I have this code:

var prodElem = $('#dropTitle').text();

$(prodElem).clone(true, true).appendTo('#orders')
 .attr("name", $(this).attr("name") + "-1");

but the name attribute is being replaced by -1.

How can I utilize "this" in order to achieve the current name and append -1 to the end?

Thanks!

0

1 Answer 1

3

this in that code doesn't refer to the element(s) you're setting the name on. My guess is this code is running where this refers to window, and so $(this).attr("name") returns the window name (which is usually blank), so you're setting name on all of those elements to "" + "-1", which is of course, "-1".

You can use the version of attr that accepts a callback:

$(prodElem).clone(true, true).appendTo('#orders')
  .attr("name", function() {
    return $(this).attr("name") + "-1";
  });

There, this refers to each matching element.

Side note: If this is really the name attribute, it's reflected by the property name, so you could also do it with prop and get the reflected attribute directly in the function:

$(prodElem).clone(true, true).appendTo('#orders')
  .prop("name", function() {
    return this.name + "-1";
  });
Sign up to request clarification or add additional context in comments.

3 Comments

But in question prodElem is simple text.
@RohitSharma - Right, and then that's passed into $(). I'm assuming the text is a selector of some kind. (But it is an assumption, quite right.)
You are correct with the assumption, my bad, thank you very much

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.