Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom attribute to HTML tags

Tags:

html

I am adding custom attributes to my HTMLtags something like

<li customeId="1">

I am to access this custom attribute in IE but in firefox, I am not able to get the values of these attributes. Any suggestion on how to access custom attribute in FireFox or any other way. I am using HTML 4 for development.

Code to access:

  var test =  licollection[index].customeId;

Thanks Ashwani

like image 873
Ashwani K Avatar asked May 13 '10 06:05

Ashwani K


People also ask

Can I add custom attribute to HTML tag?

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.

How do I create a custom data attribute in HTML?

HTML data-* Attribute The data-* attribute gives us the ability to embed custom data attributes on all HTML elements. The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

Can HTML elements have custom attributes?

Every HTML element may have any number of custom data attributes specified, with any value.

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.


2 Answers

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.

like image 108
MUS Avatar answered Sep 27 '22 22:09

MUS


You can use HTML 5 custom data attribute functionality, it may helps you

Attribute Name

The data attribute name must be at least one character long and must be prefixed with 'data-'. It should not contain any uppercase letters.

Attribute Value

The attribute value can be any string.

Example :-

<ul id="vegetable-seeds">
  <li data-spacing="10cm" data-sowing-time="March to June">Carrots</li>
  <li data-spacing="30cm" data-sowing-time="February to March">Celery</li>
  <li data-spacing="3cm" data-sowing-time="March to September">Radishes</li>
</ul>
like image 33
Gaurav Avatar answered Sep 27 '22 20:09

Gaurav