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 : http://jsfiddle.net/yccheok/ghggtrfq/4/
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 namedelem
:
$( 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:
$(function() {
var $span = $("span[data-loop]").first();
console.log($span.data("loop")); // Object {operator: "maxis"}
console.log($span.data("loop").operator); // maxis
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With