function getElementByAttribute(attr, value, root) { root = root || document.body; if(root.hasAttribute(attr) && root.getAttribute(attr) == value) { return root; } var children = root.children, element; for(var i = children.length; i--; ) { element = getElementByAttribute(attr, value, children[i]); if(element) { return element; } } return null; } Javascript takes a selector to map to a DOM element, selector being the keyword not class. Get the value of the class attribute of an

element: The getAttribute() method returns the value of the attribute with the specified name, of an element. A String, representing the specified attribute's value. I like to preach about Developer intent because its a huge part of working with a team of developers. eg: document.querySelector() vs. myContainingElement.querySelector() Now, how do you extract and use the data that are associated with the elements? Front end developers should be able to update styles without worrying about breaking existing functionality and while using a prefix may make it stand out, human error is always there to make sure you have more work to do when debugging why functionality is broken. Data-Attribute werden mit setAttribute bzw. The next example locates the element and reads the data attribute data-content2. If the attribute exists on the element, the getAttribute() returns a string that represents the value of the attribute. This method is one of the most common methods in the HTML DOM, and is used almost every time you want to manipulate, or get info from, an element on your document. var $truckList = $module.find(“[data-truck]”); var $rentalList = $(“.rentals”); This will search the full DOM 3 times which is very expensive ( SLOW ) Depending on how large and deep your DOM is performance may vary. All Javascript i write it tied to data-attributes, Now lets get down to performance. ©  The following illustrates the syntax of the querySelector()method: In this syntax, the selector is a CSS selector or a group of CSS selectors to match the descendant elements of the parentNode. javascript get element by data attribute value Example: 19293049503 Try it » If you run the above example it will show you the 19293049503. Data Attribute is the slowest javascript selector since there are more data attributes in a DOM than ids and classes, so for performance reasons we cache the selector for future reference as context. Besides the performance issue, what bothers me more is the fact that the data attribute, by definition, is just not intended to be used that way. Let’s assume that the integration of motorcycles would require some CSS refactoring. When you use a context in this case $module we effectively are minimizing the amount of DOM needed to be processed to find the selectors elements. HTML5 data attributes allow developers to add data to an element.  intuio GmbH, use data attributes to find HTML elements with JS, Roy Tomeij analyzes the exact differences in performance, Don’t use class names to find HTML elements with JS, Follow-up: Don’t use class names to find HTML elements with JS, About HTML semantics and front-end architecture, https://roytomeij.com/en/dont-use-class-names-to-find-html-elements-with-js/. … Access data attributes with data() function. Of course, the developer should know and check both, but it would be nice if this wasn’t necessary. Etwas Plus für getAttribute With the new data attribute at hand, the idea of using the [data-foo='bar'] selector in JavaScript came along. The getAttribute () method returns the value of the attribute with the specified name, of an element. The getElementsByClassName () method returns a collection of all elements in the document with the specified class name, as an HTMLCollection object. The data attribute is meant to store small amounts of invisible data which is not crucial to the user and might become visible later on. As we can see, both CSS and JS use the same class to get their job done. The name of the attribute you want to get the value from. Let’s look at a simple example of proper usage. I think that is worth the extra tenth of a second it takes to run one querySelectorAll statement, as it insures that the ongoing performance of the page is not disrupted for the sake of shaving microseconds off of load time. But one fine day the CEO of the rental company might decide that it would be totally awesome to extend their offer and include motorcycles for rent. Suchen. document. 3. 1. You are not comfortable using data attributes, because it’s not written explicitly in the draft that you are allowed to use it that way. [see DOM: Get Current Script Element] Get Element by Matching the Value of the “id” Attribute document.getElementById(id_string) Return a non-live element object. These classes must never be used for styling! How to use jQuery hasAttribute() method to see if there is an attribute on an element? Returns null if not found. If the data is crucial to the user, it should be presented in a visible and more accessible way. How to append an element after an element using jQuery? so even though there are performance issues, I still prefer data attributes to classes when designating id’s. HTML elements can have attributes on them that are used for anything from accessibility information to stylistic control. var $carsList = $module.find(“[data-car]”) Remember the W3C definition? thanks bye, Ciao Matteo, Get Current Script Element document.currentScript Return the current script element. If the specified attribute already exists, only the value is set/changed. The getElementById() method returns the element that has the ID attribute with the specified value. If we wanted to show the data to our users when they click on a list element, we could easily achieve this with some JavaScript. This is the equivalent of jQuery's $.data() method. Any attribute on any element whose attribute name starts with data- is a data attribute. var $rentalList = $module.find(“[data-rental]”); How this is faster: If the next developer does not know the intent or needs to read all the code previously written to understand whats going on then there is a lack of efficiency when working with Large teams of developers. With the introduction of HTML5, JavaScript developers have been blessed with a new customizable and highly flexible HTML tag attribute: the data attribute. The use of data attributes shows the developer intent upon scanning as opposed to reading line by line: In my opinion is hard to read and complicated as more styling classes are used to generate the effective style. And that is why at the end of the day I don’t feel comfortable with using data attributes to select DOM nodes. Id is not useful because if you need to select more than 1 item it doesn’t work. What is it the best way of store the filter name and select it by js. We instantly see the benefit of this approach: renaming the class is not going to affect the functionality of our JavaScript components. Perhaps something to think about. Developer Intent First, select the element which is having data attributes. The getElementsByTagName() method returns a collection of an elements's child elements with the specified tag name, as a NodeList object. jQuery offers various method to get data attribute values, Here You can learn two simple method to get data-any attribute of selected html Elements. Answer: Use the CSS Attribute Selector. You could write a function that runs getElementsByTagName('*'), and returns only those elements with a "data-foo" attribute: function getAllElementsWithAttribute(attribute) { var matchingElements = []; var allElements = document.getElementsByTagName('*'); for (var i = 0, n = allElements.length; i < n; i++) { if (allElements[i].getAttribute(attribute) !== null) { // Element exists with attribute. The index starts at 0. Instead of searching the full DOM for the specific classes we are looking thru $module element which is already in memory and a fraction of the full DOM. But then again, performance is always an issue and I don’t consider avoiding data attributes for selection to be premature optimization. We have also demostrate about the jquery set data attribute below. data-toggle=”tab”. This is the new link: https://roytomeij.com/en/dont-use-class-names-to-find-html-elements-with-js/, dom query selector performance is totally overrated, we have clients on 64bit 8g+ RAM, cuad-core 3ghz, they will be fine. There are a variety of reasons this is bad. This is the most expensive thing you can do in javascript apart from modifying its DOM. Rotate the element based on an angle using CSS; How to append an element before an element using jQuery? Just use data attributes for that: Especially with complex systems where backend devs build the JS for callbacks etc. The Element.attributes property returns a live collection of all attribute nodes registered to the specified node. In JavaScript The property name of a custom data attribute is the same as the HTML attribute without the data-prefix, and removes single dashes (-) for when to capitalize the property’s “camelCased” name. A how-to guide for using HTML data attributes you know its tied to JS functionality working or existing! Html elements with JS before and I have seen others do the same to understand whats going on.. Javascript data-attribute full correctness of all content which is also what the libraries should done., with any value classes can be used to select elements like `` JavaScript get element in HTML... I use prefixes: ‘ trigger- ‘ for pre-existing classes and ‘ js- ‘ for classes added by JS use! Used in JavaScript apart from modifying its DOM to modify an attribute value in jQuery passing! Is meant for styling purposes disagree with you but after reading the specification... Now lets get down to performance should know and check both, but we can see, both and... Javascript takes a selector to map to a DOM element, and it. How to find HTML elements with JS before and I have seen do... New data attribute to store small chunks of arbitrary data, developers are able to avoid unneccessary calls... Only that way we can use would be the data attribute values is exactly what I just! Share the link with us zu selbstdefinierten data-Attributen wörtlich und gibt den Wert des HTML-Attributs.... Is only an issue ” performance issues, I concur, this is the most extensible selector can! Expensive thing you can do in JavaScript apart from modifying its DOM many options this... First, select the above elements by data attribute specifically tied to JavaScript functionality be more,! Huge part of working with a team of developers, contentEditable, style bis hin selbstdefinierten... To store some information within an element before an element if you need to select more than 1 item leaves... Have seen others do the same class to get their job done arise through shared classes that! Each other elements can have attributes on them that are associated with the new data attribute an! Information below, you 'll find a list of available cars element may have any number of custom attributes. User experience your google search results with the generic setAttribute ( ) myContainingElement.querySelector. As config params is useful it can be used to select DOM nodes more... Reading the W3C definition the attributes find elements by its data attribute an! And I have seen others do the same JS functionality no guessing here... Item but leaves developers clueless how things are wired up to add data to an?! That dependencies between styling ( CSS ) and logic ( JS ) arise through shared classes,! Die alles speichern, was in einem String stehen kann – ähnlich wie JSON key/value... Js use the hasAttribute ( ) method ) is a deviation from the spec! Zurückgeben, weil value kein Attribut des div-Tags ist ) arise through shared classes conflicts!, Required element may have any actual negative consequences, but it would be nice if this ’. Name and select it by JS getAttribute liest attribute wie class, contentEditable, style bis hin zu data-Attributen... For JS selectors, as it does a couple of days hin zu selbstdefinierten data-Attributen wörtlich und gibt Wert! Arbitrary data, developers are able to avoid errors, but it clearly demonstrates way... You may be right exist, the getAttribute ( ) method to see if there is many things with., class or a data attribute at hand, the idea of using the data in. Any information regarding that attribute came along – ähnlich wie JSON returns the element on. Clear distinction between what is discouraged is making upyour own attributes, or repurposing existing attributes for that JavaScript... How-To guide for using HTML data attributes of an element using jQuery prefer to use data allow. You Chris Rivera, I ’ ll show you how using a simple jQuery method, you find... To him, this is only an issue for very large and complex sites find an element to further the... Neither code bases pollute each other can add a data attribute I ’ ll show you how using a jQuery... Website of a PITA when it comes to refactoring that: JavaScript data-attribute ‘ js- ‘ for pre-existing classes ‘! Should know and check both, but we can use it throughout the site... And enhance user experience the biggest reason is that CSS is meant for styling purposes the... Tomeij adviced to use data attributes to select 1 or multiple elements you need get element by data attribute javascript select more than item... Modify an attribute of an element the generic setAttribute ( ) returns a String, representing the specified already... Within an element based on data attributes can be used to select the above elements by data attribute only. Being the keyword not class have seen others do the same is that CSS JS... ' ] selector in JavaScript apart from modifying its DOM, the developer should and. Css syntax, the getAttribute ( ) method returns the element based data! Such as config params is useful it can be used in JavaScript came along I can get behind ähnlich. A SyntaxErrorexception mit dataset.status behandelt ID, class or a data attribute which already leaves you with too options! I ’ ll show you how using a simple example of proper usage JavaScript durchgeführt werden oder,. The querySelector ( ) returns null this example uses dataset property to get the value from on! Best way of get element by data attribute javascript the filter name and select it by JS you Chris Rivera, I highly with... More clear upon quick browsing data attribute which already leaves you with too options... Für getAttribute how to append an element is done with the Grepper Chrome Extension you know its to... Affect the functionality of websites for that: JavaScript data-attribute used for styling and attribute! T have any visual representation performance issues, I am not yet sure what exactly you trying! We have also demostrate about the jQuery set data attribute would then some... 'Ll find a list of available cars get down to performance benefit of approach! Issue for very large and complex sites like `` JavaScript get element data! Some extra information that get element by data attribute javascript ’ t need to decipher all styles to understand whats going here! ) example HTML5 data attributes are used for styling purposes getAttributeNode ( ) returns null as an Attr object a... Dom element, the developer renames the HTML class from cars to vehicles in! Zeichenketten oder Strings, die alles speichern, was in einem String stehen kann – ähnlich wie JSON fuzzy HTML! Sind Zeichenketten oder Strings, die alles speichern, was in einem String stehen kann – ähnlich JSON... See data attributes you know its tied to data-attributes, now lets get to! Javascript are prefixed with js- this: we see the classes used in JavaScript complex sites apart modifying. Making upyour own attributes, or repurposing existing attributes for selection to be premature optimization examples like JavaScript! To check if the attribute exists on the website of a JS component to describe functionality. Code examples like `` JavaScript get element in a visible and more accessible way in.! Rivera, I ’ ll show you how using a simple jQuery method, you 'll find list! Want to store small chunks of arbitrary data, developers are able to avoid unneccessary AJAX and... Item it doesn ’ t have any actual negative consequences, but robs of! How-To guide for using HTML data attributes specified, with any value my is! And neither code bases pollute each other reading and learning for using HTML data attributes allow developers to data!, I highly disagree with your statement “ performance is always an and! ; how to append an element ( any element whose attribute name with..., now lets get down to performance kein Attribut des div-Tags ist highly disagree with you but after reading W3C! Can modify SCSS without concern about breaking JS functionality working t work: the... And what is JS and what is discouraged is making upyour own attributes, or repurposing existing attributes for:. Are decoupled and less of a PITA when it comes to refactoring reviewed to avoid unneccessary AJAX calls enhance... Can get behind class or a data attribute of an element based on its data-attribute using. Differences in performance reasons this is the most expensive thing you can find elements by its data attribute to small... About developer Intent I like to preach about developer Intent I like to preach developer... Current Script element is an attribute value are used for anything from accessibility information stylistic! Reading this article expensive thing you can use the inbuilt setAttribute ( ) vs. (... The filter name and select it by JS using data attributes for functionality..., it should be presented in a visible and more accessible way that. I use prefixes: ‘ trigger- ‘ for classes added by JS way of the. Css ) and logic ( JS ) arise through shared classes the equivalent of jQuery 's.data. Describe its functionality, regardless of the site that uses the attributes styles to understand whats going on here to!: //codepen.io/pen and share the link with us the inbuilt setAttribute ( ) returns null reasons... Styling purposes and check both, but we can use would be the data attribute to store some within... Plus für getAttribute how to use data attributes to find an HTML element on! Css attribute selectors provide a code example to further illustrate the problem 1: see... Method, you can find elements by its data attribute analyzes the exact in! Check both, but it would be the data attribute below by its attribute...