Change this .attr() to use a data-rel instead

Hi there,

I have the following code which adds a caption based on an image’s alt tag.

var description = $( 'a[href="' + $( '#imagelightbox' ).attr( 'src' ) + '"] img' ).attr( 'alt' );

With the following HTML:

<a href="images/large-1.jpg" data-imagelightbox="a"><img src="images/hotel/small-1.jpg"  alt="sadsadasdasdad" /></a>

What I would like to do is to use thhe following as the caption: data-caption=“my description”

I’ve tried this, but it doesn’t work:

var description = $( 'a[href="' + $( '#imagelightbox' ).attr( 'src' ) + '"] img' ).attr( 'data-caption' );

Any ideas what I have wrong?


I’d say the selector matches nothing. you would first need to verify that the selector is what you assume it to be (e.g. use console.log).

note. data attributes are fetched with .data(), .attr() may have problems, if the data attribute was set via JS.

.attr('data-caption') is the getter for the given attribute; to set it, you’ll also have to pass a value, like .attr('data-caption', 'my description')

As @Dormilich noted, you can also simply use the .data() method; however, the difference is that it only stores the dataset internally, so you can’t use it as a selector (say). Consider:

$('div').data('foo', true)
console.log($('div').data('foo'))           // true
console.log($('div[data-foo]').data('foo')) // undefined

// But:
$('div').attr('data-foo', true)
console.log($('div').data('foo'))           // true
console.log($('div[data-foo]').data('foo')) // true

So which to use depends on what you’d like to do with it. .data() is more versatile for storing data (you can access the full dataset as a single object), but it doesn’t actually get written to the DOM.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.