Search code examples
htmlcustom-data-attribute

Should I not use data attributes in html?


I am coding a C# forms application that lets a user add custom html nodes to a html webpage. I have some javascript code that selects a html node to execute specific code for objects such as a jQuery ui slider.

To identify html nodes, I need to store an attribute in the tag that identifies the tag.

I am new to writing html code, and as such, I would like to ask if there is any reason why I should not use data attributes for tags? Are there any limitations are disadvantages that I should be aware of?

Here is some example code that I have currently working:

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div data-customwebpagelayout-name='slider-increments'>
    <div data-customwebpageobject-name='slider-increments'></div>
</div>

<p data-customwebpageobject-output-name='slider-increments'>1</p>

</body>
</html>

Thank you.


Solution

  • The common way to identify and select HTML tags is with either class or id.

    If there is only going to be one of something on a page, you should use id. It looks like you have multiple of the same thing you want to identify, so I'd use class like so:

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    
    <div class="customwebpagelayout slider-increments" >
        <div class="customwebpageobject slider-increments"></div>
    </div>
    
    <p class="customwebpageobject slider-increments">1</p>
    
    </body>
    </html>
    

    Then you could select the nodes with javascript like so:

    document.getElementsByClassName("slider-increments");
    

    or if you decide to use jQuery:

    $(".slider-increments");
    

    Data attributes are more of a pain to work with:

    Raw Javascript (code adapted from code in this answer):

    var matchingElements = [];
    var allElements = document.getElementsByTagName('*');
    for (var i = 0, n = allElements.length; i < n; i++){
      if (allElements[i].getAttribute('data-customwebpagelayout-name') !== null){
        // Element exists with attribute. Add to array.
        matchingElements.push(allElements[i]);
      }
    }
    //use matchingElements;
    

    jQuery:

    $("*[data-customwebpagelayout-name='data-customwebpagelayout-name']");