Given a section of HTML, can I selectively pick some types of elements (e.g., input) and add a custom attribute using JavaScript? I would also need to remove this attribute if it exists.
I have done this before using jQuery, but I'm unable to use it for this particular task.
So how do we add custom attributes to HTML elements? We can create any custom attribute, by adding, data-, followed by the attribute name.
If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery.
The setAttribute() method sets a new value to an attribute.
You can use getAttribute() and setAttribute() in JavaScript to get and set the value of different data attributes. The getAttribute method will either return null or an empty string if the given attribute does not exist. Here is an example of using these methods: var restaurant = document.
Accessing HTML attributes using the DOM
element.hasAttribute('foo'); element.getAttribute('foo'); element.setAttribute('foo', value); element.removeAttribute('foo');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With