Can I add a custom attribute to an HTML tag like the following?
Yes, you can do it!
Having the next HTML
tag:
<tag key="value"/>
We can access their attributes with JavaScript
:
element.getAttribute('key'); // Getter
element.setAttribute('key', 'value'); // Setter
Element.setAttribute()
put the attribute in the HTML
tag if not exist. So, you dont need to declare it in the HTML
code if you are going to set it with JavaScript
.
key
: could be any name you desire for the attribute, while is not already used for the current tag.
value
: it's always a string containing what you need.
You can add, but then you have to write a line of JavaScript code too,
document.createElement('tag');
to make sure everything fall in place. I mean Internet Explorer :)
You can do something like this to extract the value you want from JavaScript instead of an attribute:
<a href='#' class='click'>
<span style='display:none;'>value for JavaScript</span>some text
</a>
The jQuery data()
function allows you to associate arbitrary data with DOM elements. Here's an example.
Yes, you can use data-*
attribute.
The data-*
attribute is used to store custom data private to the page or application.
<ul>
<li data-pageNumber="1"> 1 </li>
<li data-pageNumber="2"> 2 </li>
<li data-pageNumber="3"> 3 </li>
</ul