jQuery: Select data attributes that aren’t empty?

Just as further reference, and an up-to-date (may’14) (aug’15) (sep’16) (apr’17) (mar’18) (mar’19) (may’20) (jan’22)… Answer that works with: ###Empty strings: If the attr must exist & could have any value (or none at all) jQuery(“[href]”); ###Missing attributes: If attr could exist & if exist, must have some value jQuery(“[href!=”]”); ###Or both: If attr must … Read more

How can I use a data attribute to set a background-image in CSS?

This won’t be possible with pure css unless you’re doing it the “undynamic” way: .slide[data-bg=”one”]{ background-image: url(‘img/one.jpg’); } .slide[data-bg=”two”]{ background-image: url(‘img/two.jpg’); } … Maybe you can dynamically create that stylesheet from your filenames on server-side. Another (likely easier) possibility is to do this with JavaScript – but since you excluded that I assume you know … Read more

JQuery .data() not working?

data doesn’t set data-* attributes. It manages a data cache unrelated to data-* attributes. It initializes from data-* attributes if there are any present, but never writes to them. To write to an attribute, use attr. Example: Updated Fiddle var div = $(“<div />”) $(div).attr(“data-foo”, “bar”) console.log($(div)[0].outerHTML) What you’re seeing is just one of the … Read more

Is there any problem with using HTML5’s “data-*” attributes for older browsers?

There isn’t really, they’re not 100% correct/valid usage in HTML4 of course….but they don’t cause problems either, so they’re still a great way to solve the “I need an attribute for this” problem. If it helps, I’ve used these while supporting IE6 and have had zero issues thus far, and I can’t recall a single … Read more