1

I try to get an attribute of a div element using jQUery 1.6.2

html

<div id="scroller" loop="2"></div>

js

$('#scroller').attr('loop') 

The above js would always return undefined.

I try to upgrade jquery to 1.6.4, then the same js returns me the word 'loop'. Is this loop attribute a reserved attribute?

I do this becoz of using a library for scrolling text.http://remysharp.com/2008/09/10/the-silky-smooth-marquee/

3 Answers 3

3

What's really going on is jQuery's implementation of attr. loop is a boolean attribute for media (<audio> and <video>) elements, so its presence indicates that the audio or video should loop.

When boolean attributes are used, it is invalid to specify a value other than the attribute name itself. When jQuery checks a boolean attribute, it returns the name of the attribute itself. In this case [loop]'s value is its name: "loop".


You shouldn't be adding custom attributes to elements unless you're using the [data-] attributes specified in HTML5:

<div id="scroller" data-loop="2"></div>

jQuery supports accessing these [data-] attributes with the data function:

$('#scroller').data('loop'); //returns "2"
Sign up to request clarification or add additional context in comments.

4 Comments

This is exactly right. I would also be curious about the role of the "loop" variable. Surely if it's for tracking the number of loops, this is something that can be stored in a JS variable rather than in a DOM node? I don't see any "loop" in Remy's markup.
@xdazz, then my second point still stands. You shouldn't make up your own attributes unless you're using [data-] attributes.
@zzzzBov Yep, you are right, but I would like to know the reason and why loop is special?
Despite the age of this post - it may be useful to others to know that while the answer from @zzzzBov above is correct, you can also get the bool value for loop in jQuery using the .prop method. e.g. $el.prop('loop')
1

Maybe, "loop" is some predefined value into jQuery. So, it is a jQuery bug.

Use simple JS for this:

document.getElementById("scroller").getAttribute("loop")

Comments

0

It seems that it is a bug.

document.getElementById("scroller").getAttribute("loop") will return 2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.