2

In HTML I have a div with various data- attribute properties set within a JSON object, e.g.:

<div data-layout='{
      "type" : "header",
      "minHeight" :  "10%"
   }'>
   Layout
</div>

In code, is it possible to select only elements which have e.g. data-layout.type==="header" without using .each or a filter function?

I'm looking for something along the lines of:

$('[data-layout]').find('type="header"')
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
4EverLive
  • 111
  • 1
  • 8
  • Kinda, you can use *= to see if `"type" : "header"` appears anywhere within the value of the attribute, however it would be far less prone to issues if you just use .filter. – Kevin B May 01 '13 at 18:28
  • I think this link will help you: http://stackoverflow.com/questions/2891452/jquery-data-selector – uross May 01 '13 at 18:30
  • If the data-* attribute is set as simple ("key", "value") I can use attribute selector such as '[key="value"]'. My question is if I can do something similar to select the property of a JSON object as shown in my example, or is .filter the only way. data-layout is not set to a single (string) value but a JSON object. I'm needing to select elements with data-layout attributes having certain properties set to a specific value. – 4EverLive May 01 '13 at 18:32
  • Thanks uross, only saw your comment after mine. This is what I'm looking for. – 4EverLive May 01 '13 at 18:33
  • No problem, I am glad I could help. I have added this in answer, so you can mark it as resolved. – uross May 01 '13 at 18:38

2 Answers2

3

If you do not use header anywhere else in the data-layout attribute you can use the attribute contains selector like this:

$('*[data-layout *="header"]')
0

Using function from this answer, you can use pattern described below:

:data( {namespace} [{operator} {check}]  )

"operator" and "check" are optional. So, if you only have :data(a.b.c) it will simply check for the truthiness of a.b.c.

Read more about it here.

Community
  • 1
  • 1
uross
  • 431
  • 5
  • 12
  • Thanks. The answer provided by Austin also works as long as "header" is not used elsewhere in the data-layout attribute object, but I'm specifically needing to find elements with (e.g.) someAttrProp===someValue. – 4EverLive May 01 '13 at 18:45