Storing data in the DOM

前端 未结 3 1841
名媛妹妹
名媛妹妹 2021-01-13 11:32

I have a list of books and I want to store data against each book e.g. Price, Quantity, id, catergory id, size, weight etc.

I was looking at storing all this in the

3条回答
  •  被撕碎了的回忆
    2021-01-13 11:32

    The difference between storing that in the DOM elements and keeping data as JavaScript objects is that in the first case you have the data and the DOM element directly related, while in the second case you need to somehow keep similar data and DOM structures in order to keep the data related to the DOM. The second case is, as it sounds, more error prone, because you have to make sure that every change in the DOM is reflected in the data (adding/removing/modifying elements) and every change in the data is reflected in the DOM (adding/removing/modifying data members).

    In the case of data-* attributes data is directly accessed from the DOM so the two are already tied together and is, at least in my opinion, a much better practice. However, as mentioned in comments, there is a DOM retrieval overhead which comes with data-* attributes.

    In terms of performance both require the data to be stored in memory, be it as DOM element attributes or as JavaScript objects. Retrieving a DOM element attribute is actually more expensive but it's more convenient. Rendering is not affected by data-* attributes as they do not have any functional meaning.

提交回复
热议问题