Is “loop” a special keyword within span?

I have the following HTML:

<span loopx='{"operator":"maxis"}'>hello</span>

If I want to retrieve its attribute value {"operator":"maxis"}, I can simply use

$('span[loopx]').each(function(index) {
    var attr = $(this).attr('loopx');
    // attr is the string "{"operator":"maxis"}"

However, for the following HTML

<span loop='{"operator":"maxis"}'>world</span>

I get the following result:

$('span[loop]').each(function(index) {
    var attr = $(this).attr('loop');
    // attr is the string "loop"

I was wondering, if loop is a special keyword within span?

Here’s the test code :

There is no loop attribute in span elements: global attributes only.

However, there is a loop attribute in audio and video elements.

For custom attributes, you should use data attributes as defined in HTML5.

If you name your attribute data-loop, you can natively access it through element.dataset.loop.

According to specs, loop is a boolean attribute, which means you must specify it in one of the following ways**:

<span loop>
<span loop="">
<span loop="loop">

Any other value such as loop="false" or loop="0" or loop='{"operator":"maxis"}' just imply that the loop attribute is present and the audio/video would loop.

Now, for boolean attributes jQuery.attr simply returns the attribute name. This behavior is documented and it is not a bug:

Concerning boolean attributes, consider a DOM element defined by the
HTML markup <input type="checkbox" checked="checked" />, and assume
it is in a JavaScript variable named elem:

$( elem ).attr( "checked" ) (1.6.1+) (returns) "checked"
(String) Will change with checkbox state

Having explained that, the correct solution is to use the HTML5 data attributes. jQuery parses data attributes on page load so you can do this:

Read More:   Better alternative to an iframe to display tab content?

$(function() {
  var $span = $("span[data-loop]").first();
  console.log($"loop")); // Object {operator: "maxis"}
  console.log($"loop").operator); // maxis
<script src=""></script>

<span data-loop='{"operator":"maxis"}'>world</span>

** Note that this attribute is invalid on span elements.

loop is an attribute used in html5 media tags that expects a boolean true or false value. I expect this is why the above isn’t working.

I think is a jQuery bug, with vanilla Js it works without problems

var span = document.getElementsByTagName( 'span' );
for ( var i = 0, len = span.length; i < len; i++ ) {
  var out = document.querySelector( '#out'+ (i+1) );
  out.innerHTML = span[i].getAttribute( 'loopx' ) + span[i].getAttribute( 'loop' );
<pre id="out1"></pre>
<pre id="out2"></pre>

<span loopx='{"operator":"maxis"}'>hello</span>
<span loop='{"operator":"maxis"}'>world</span>

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts