0

As the title says, I would like to add a new hidden attribute to an element. To avoid any confusion, I want the attribute to be hidden, not the element.

I have a div: <div id="hello_div">Hello!</div>

I add an attribute: $('#hello_div').attr('my_attr', 'attr_value');

So I can get it later: var v = $('#hello_div').attr('my_attr');

It works as expected but if you inspect the div in the DOM Explorer, you see:

<div id="hello_div" my_attr="attr_value">Hello!</div>

Is there any way to hide this attribute?

Arthur Rey
  • 2,990
  • 3
  • 19
  • 42

3 Answers3

5

You can't hide DOM-attributes, but as I see you are using jQuery, you could try data. E.g.

$('#hello_div').data('my_attr', 'attr_value');

and later retrieve:

var v = $('#hello_div').data('my_attr');
nhaa123
  • 9,570
  • 11
  • 42
  • 63
2

When you get back your required attribute var v = $('#hello_div').attr('my_attr');

remove the attribute after this $('#hello_div').removeAttr('my_attr');

danish farhaj
  • 1,316
  • 10
  • 20
0

No. If you manipulate the DOM by adding an attribute, it will always be visible when using a DOM inspector like Chrome developer tools etc.

B_s
  • 3,026
  • 5
  • 32
  • 51