Can I add a custom attribute to an HTML tag?
You can amend your !DOCTYPE declaration (i.e. DTD) to allow it, so that the [XML] document will still be valid:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
[
<!ATTLIST tag myAttri CDATA #IMPLIED>
]>
#IMPLIED
means it is an optional attribute, or you could use #REQUIRED
, etc.
More information is in DTD - Attributes.
Add custom attribute to HTML tags
Hopefully below code will be helpful for you.
<div id="navigation">
<ul>
<li customerId="1"></li>
<li customerId="2"></li>
<li customerId="3"></li>
</ul>
</div>
var x = document.getElementById('navigation');
if (!x) return;
var liCollections = x.getElementsByTagName('li');
for (var i=0;i<liCollections.length;i++)
alert(liCollections[i].getAttribute('customerid', 0));
It's clear enough, and you can understand it easily.
How to add custom attributes to standard HTML elements?
The data-*
attribute are custom attributes; they're only use to store specific data that the web developer will use it in tater time in his code in JavaScript.
<button id="mybutton" class="btn btn-primary" data-intro-step="4" data-bind-action="matchmake-mp-role" data-track="playnow.matchmake.cqclassic.join" data-bind-intro="next" data-expansion="0" data-game="2048" data-platform="1" data-role="1" data-experience="1">
Play now
</button>
For example to access the data-intro-step
value from jquery, developer may type $('#mybutton').attr('data-intro-step')
or $('#mybutton').data('data-intro-step')
and use it with somethiing in his code.
Usually they're add from php or a js framework like jquery-plugins
or angularjs
, and used in js. put you could also add them from js to use it later.
Adding custom attributes in html tags
No side effects that I know if, they just won't validate and it's possible that in the future whatever attribute name you choose may conflict if browsers decide to implement one with the same name (Unlikely if you name it something unique enough)
Read more here: Custom attributes - Yea or nay?
How to add custom html attributes in JSX
EDIT: Updated to reflect React 16
Custom attributes are supported natively in React 16. This means that adding a custom attribute to an element is now as simple as adding it to a render
function, like so:
render() {
return (
<div custom-attribute="some-value" />
);
}
For more:
https://reactjs.org/blog/2017/09/26/react-v16.0.html#support-for-custom-dom-attributes
https://facebook.github.io/react/blog/2017/09/08/dom-attributes-in-react-16.html
Previous answer (React 15 and earlier)
Custom attributes are currently not supported. See this open issue for more info: https://github.com/facebook/react/issues/140
As a workaround, you can do something like this in componentDidMount
:
componentDidMount: function() {
var element = ReactDOM.findDOMNode(this.refs.test);
element.setAttribute('custom-attribute', 'some value');
}
See https://jsfiddle.net/peterjmag/kysymow0/ for a working example. (Inspired by syranide's suggestion in this comment.)
custom HTML tags and attributes
I ran your code and it worked just fine with the constructor
, but you could try connectedCallback
instead. This method gets called any time an element is added to the document.
Make sure your script runs in the <head>
of the document, before your <body>
is executed. HTML/scripts run top-to-bottom. Your element needs to be registered before it is rendered.
Update: Please refer to the "Custom elements" - JavaScript.info article that was linked by Martin Braun for a better understanding. The official MDN documentation can be viewed here: "Using custom elements" - MDN.
class MyTrophy extends HTMLElement {
connectedCallback() {
const rarity = this.getAttribute('rarity');
console.log(`Rarity: ${rarity}`);
}
}
customElements.define('my-trophy', MyTrophy);
my-trophy {
font-size: 3em;
}
my-trophy[rarity="silver"] {
color: #777;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet"/>
<my-trophy class="fas fa-trophy" rarity="silver"></my-trophy>
Custom attribute binding in HTML
There are several ways to accomplish this:
Interpolation
attr.data-target="collapse{{id}}"
Attribute binding
[attr.data-target]="'collapse' + id"
Attribute binding canonical form
bind-attr.data-target="'collapse' + id"
Using custom method
ts
getTarget(id) {
return `collapse${id}`;
}
html
[attr.data-target]="getTarget(id)"
or
bind-attr.data-target="getTarget(id)"
Live example on ng-run
Create custom tags/attributes using JavaScript
Why yes, yes you can. In fact, they're a stable part of the web components standard.
Custom Elements is a capability for creating your own custom HTML
elements. They can have their own scripted behavior and CSS styling.
They are a part of web components, but can also be used by themselves.It may be unclear as to why the new custom elements capability was
created, as it was already possible to create a tag name like<mytag>
and style it with CSS, then use scripting to attach behaviors to it.
An advantage that custom elements have are their lifecycle reactions,
which allow attaching behaviors to different parts of the new
element's "lifecycle." For example, a certain behavior can be attached
for when the element is inserted into the DOM ("connected"), and a
different behavior when it is removed from the DOM ("disconnected"),
or when its attributes change.
Example
// Create a class for the elementclass XProduct extends HTMLElement { constructor() { // Always call super first in constructor super();
// Create a shadow root var shadow = this.attachShadow({mode: 'open'});
// Create a standard img element and set its attributes. var img = document.createElement('img'); img.alt = this.getAttribute('data-name'); img.src = this.getAttribute('data-img'); img.width = '150'; img.height = '150'; img.className = 'product-img';
// Add the image to the shadow root. shadow.appendChild(img);
// Add an event listener to the image. img.addEventListener('click', () => { window.location = this.getAttribute('data-url'); });
// Create a link to the product. var link = document.createElement('a'); link.innerText = this.getAttribute('data-name'); link.href = this.getAttribute('data-url'); link.className = 'product-name';
// Add the link to the shadow root. shadow.appendChild(link); }}
// Define the new elementcustomElements.define('x-product', XProduct);
body { background: #F7F7F7;}
x-product { display: inline-block; float: left; margin: 0.5em; border-radius: 3px; background: #FFF; box-shadow: 0 1px 3px rgba(0,0,0,0.25); font-family: Helvetica, arial, sans-serif; -webkit-font-smoothing: antialiased;}
x-product::slotted(.product-img) { cursor: pointer; background: #FFF; margin: 0.5em;}
x-product::slotted(.product-name) { display: block; text-align: center; text-decoration: none; color: #08C; border-top: 1px solid #EEE; font-weight: bold; padding: 0.75em 0;}
If nothing appeared below, then your browser does not support Custom Elements yet.<x-product data-name="Ruby" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/ruby.png" data-url="http://example.com/1"></x-product><x-product data-name="JavaScript" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/javascript.png" data-url="http://example.com/2"></x-product><x-product data-name="Python" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/python.png" data-url="http://example.com/3"></x-product>
Related Topics
How Does the "Position: Sticky;" Property Work
How to Replicate Background-Attachment Fixed on Ios
Why Does Position:Relative; Appear to Change the Z-Index
Changing Image on Hover With Css/Html
Display Pdf Within Web Browser
Why Is 'Position: Sticky' Not Working With Core Ui'S Bootstrap Css
Is It Bad to Use !Important in a CSS Property
Preventing Double Borders in CSS Grid
Are There Any Style Options For the Html5 Date Picker
Responsively Change Div Size Keeping Aspect Ratio
How to Add an HTML Link in the Body of a Mailto Link
Why Can't I Have a Numeric Value as the Id of an Element