JQuery: how can I add useful information to my page elements?

I am tempted to make some custom attributes for some page elements to make it easier to select using a function .attr();in jQuery.

I believe this is probably not recommended, as there is great flexibility in jQuery and javaScript, which, as a beginner, I have not yet learned to use all my features.

Besides creating cryptographic identifiers or adding a large number of classes, what are some ways to add additional information to my divs and other page elements for easy selection with a selector $()?

I'm most curious about the pros and cons, and what kind of memory problems or performance issues arise based on different approaches.

+3
source share
9 answers

There is no problem creating custom attributes for your elements. In any case, you must follow the specifications html5 data-.

<div id="foo" data-info="hello" data-more="{'iam': 'anobject'}" />

The most interesting thing about using this: jQuery (latest version) automatically parses attributes data-xand adds them to .data()expando.

$('#foo').data('info') === 'hello'
$('#foo').data('more').iam === 'anobject'

You can still trigger the selector, for example

$('div[data-info=hello]')

on your items.

ref . : . data () , html5 data attributes

+5
source

HTML5 data-* . , , .

.data() jQuery . , .

+2

jQuery , "rel" "title", jQuery .data(), javascript. .

http://api.jquery.com/jQuery.data/

.

+1

, , , jQuery . - (//// ..). , , .

, . - , , ( jQuery CSS - ). , HTML , jQuery / . (, , .)

+1

, attr(). . , javascript, . - !

+1

A unique identifier is the fastest way to find an element through jQuery, so if the goal of your temptation is to simplify your elements for jQuery, this seems pointless.

I used methods to add attributes like title or alt for better accessibility.

0
source

Use .data('key', 'val')to set your data and .data('key')to read it.

0
source

I would definitely use the Data api ( http://api.jquery.com/jQuery.data/ )

0
source

Source: https://habr.com/ru/post/1784770/


All Articles