Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for adding a custom attribute to some elements

Tags:

javascript

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.

like image 534
DotnetDude Avatar asked Apr 16 '09 19:04

DotnetDude


People also ask

How do I add a custom attribute to an element?

So how do we add custom attributes to HTML elements? We can create any custom attribute, by adding, data-, followed by the attribute name.

Can we add custom attributes to HTML elements?

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.

What method allows us to add an attribute to a DOM element?

The setAttribute() method sets a new value to an attribute.

What is the recommended way to add custom HTML5 attributes?

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.


1 Answers

Accessing HTML attributes using the DOM

element.hasAttribute('foo'); element.getAttribute('foo'); element.setAttribute('foo', value); element.removeAttribute('foo'); 
like image 105
Luis Melgratti Avatar answered Sep 19 '22 22:09

Luis Melgratti