Home > Mobile >  Is it okay to use attributes from a tag in another tag?
Is it okay to use attributes from a tag in another tag?

Time:01-12

I would like to know if it is a problem to use an attribute of a tag in another tag, which does not have this attribute.

For example: in the <video> attribute we have src. If I put <p src="..."> will there be any problem? I know it's wrong, but it's just a question!

I ask this because I can capture the src attribute inside P using javascript. Example:

var tag = document.getElementsByTagName("p") 
for (var i = 0; i < tag.length; i  ) {
    alert(tag.item(i).getAttribute("src"))
}
<p src="...">Hello!</p>

I would like to know if there is any limitation for this, or if there will be any incompatibility.

Thanks.

CodePudding user response:

You can use an attribute with data- preffix for that purpose.

Custom data attributes are intended to store custom data, state, annotations, and similar, private to the page or application, for which there are no more appropriate attributes or elements.

source: https://html.spec.whatwg.org/#custom-data-attribute

So, in your case it could be something like that:

var tag = document.getElementsByTagName("p") 
for (var i = 0; i < tag.length; i  ) {
    alert(tag.item(i).getAttribute("data-src"))
}
<p data-src="...">Hello!</p>

If you don't do that, you may face compatibility issues in the future.

CodePudding user response:

No limits. In fact in HTML5 spec you can define your own custom nodes.

Indeed adding additional attributes to exiting element (such as a p) will yield best-practice warnings.

https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#elements-in-the-dom

However there is a convenient place for custom attributes within the data-* attributes:

<p data-src='//custom/path.png'></p>

Then you have the added bonus of the js dataset:

let $node = $('p')
$node.dataset.src == '//custom/path.png'

https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes

But also you can also invent your own nodes:

<mycustomnode></mycustomnode>

Aside from that - go nuts!

CodePudding user response:

Better avoid using attributes that are not part of the tag. Use the data attributes for that:

const tag = document.querySelector('p');
console.log({
  foo: tag.dataset.foo,
  moo: tag.dataset.moo
});
<p data-foo="bar" data-moo="goo">Hello dataset</b>

Docs: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

  • Related