0
 var $div = $('<div/>', {
         css: css,
         id: "testId" + product.id
 });

How can I access this id from this $div..

For now I hardcoded it when fetching from html, like this:

$('#testId_a2732d9e-db81-4c2f-85aa-563856e53ff4').css('background', '');

But I would like to access it directly in my javascript file from this $div

Thanks

3
  • $div.prop('id') Commented Nov 23, 2019 at 14:22
  • @RoryMcCrossan Thanks for help mate, looks like it's fetching id, but now it says $div.prop(...).css is not a function, what that might be Commented Nov 23, 2019 at 14:33
  • That's because prop() returns a string. You can't call css() on a string, you need a jQuery object, which is in the $div variable. Commented Nov 23, 2019 at 15:18

3 Answers 3

1

Use the attr() method to get any attribute value.

$div.attr('id')
Sign up to request clarification or add additional context in comments.

3 Comments

Use prop() when dealing with properties of the Element object.
Yes, but id HTML attribute has 1:1 mapping to property. So, in this case we would be getting the same result. Right?
@KumarSwapnil Probably, but when you want an element's property, it's better to use .prop() than to use .attr().
0

As long as you have access to this variable, then

$div.attr('id')

2 Comments

Use prop() when dealing with properties of the Element object.
@RoryMcCrossan Yes
0

You can use .prop():

var product = { id: "abcd" };

var $div = $('<div/>', {
   id: "testId" + product.id
 });
 
 console.log($div.prop('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2 Comments

Thanks for help, but now with this modifications I got this error ` $div.prop(...).css` is not a function
@Roxy'Pro You said you wanted to get the ID. The ID is a string, so it doesn't have a .css() method. What are you trying to do?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.