0

I want to clarify what would be a proper way to getting and manipulating product ID. Here is my attempt:

HTML:

<div data-product-id="100"></div>

Script:

var pid = $(this).attr('data-product-id');
$('#product_' + pid).css('display', 'none');

Is there a better way that $('#product_' + pid)?

Cudos
  • 5,733
  • 11
  • 50
  • 77

4 Answers4

1

The only problem I can use is not using data() to access data attributes, otherwise using product id number and concatenating it with for prefix like product_ is fine if you do not have a lot of elements otherwise you can use p_ to save some bytes.

To see the difference between data() and attribute you can read this article.

var pid = $(this).data('product-id');
$('#product_' + pid).css('display', 'none');
Community
  • 1
  • 1
Adil
  • 146,340
  • 25
  • 209
  • 204
1

Why not simply do it like:

$('#product_id').hide();

but if you insists:

$('#product_' + $(this).data('product-id')).hide();
palaѕн
  • 72,112
  • 17
  • 116
  • 136
0

Try this:

 $('#product_' + $(this).data('product-id')).css('display', 'none');;
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
0

The only real problem with your code is that it wouldn't work for any id. For example it wouldn't work if you have dots or parenthesis inside your data attribute.

In that case, you would have to do

$(document.getElementById('product_' + $(this).data('product-id')))
    .css('display', 'none');

If you know what ID you have, and that they're not fancy, then your code is mostly fine.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758