Mazatec
Mazatec

Reputation: 11649

jquery how to find element searching against attribute name

I have a quite specific query, how can I find all elements with a certain attribute.

My elements have attributes which follow a specific pattern, here are some examples:

 <div data-jtemplate-href="x"></div>
 <span data-jtemplate-text="x"></span>
 <input data-jtemplate-something="x"/>
 <table data-jtemplate-else="x"></table>

as you can see, all my elements have attributes where the name has the prefix 'data-jtemplate', how can I find all elements with the attribute prefix data-jtemplate?

Upvotes: 1

Views: 255

Answers (3)

Vitaly
Vitaly

Reputation: 714

I would suggest that you convert your mark up according to this:

<div "data-jtemplate"="href-x"></div>
<span "data-jtemplate"="text-y"></span>
<input "data-jtemplate"="something-z" />
<table "data-jtemplate"="else-v"></table>

now you can do a pretty simple search:

var jTemplate = $("*[data-jtemplate]") // selects all elements with that prefix
$("*[data-jtemplate^='href-']", jTemplate) // select all elements with href in jTemplate scope
$("*[data-jtemplate^='text-']").each( function(i, ele)
{
   var attr = $(this).attr("data-jtemplate").replace("text-",""); // gives you actual value of the attribute
});

UPDATE:

<div 'data-jtemplate'='{href:"http://example.com",text:"example",attr:10,private:false}'></div> 
// {href:"http://example.com",text:"example",attr:10,private:false} -> easy to create on the server

var json = $("[data-jtemplate]").eq(0).attr("data-jtemplate");
var parsedData = $.parseJSON(json);
var href = parsedData.href; // etc -- easy to access

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

Create your own expression, see http://jsfiddle.net/6pCh4/

$.expr[":"].dataAttrStartingWith = function(el, i, m) {
  for (var p in $(el).data()) {
     if (p.substring(0, m[3].length) === m[3]) return true;    
  }
  return false;
};  


console.log($('body *:dataAttrStartingWith(jtemplate)'))

this expression will filter all elements with a data-jtemplate-* attribute (As you can see in the fiddle I've added another element that was correctly discarded by this filter)

Of course this is customizable with other data-* attribute (just change jtemplate in the selector)

Upvotes: 3

Blazemonger
Blazemonger

Reputation: 92893

Just add another attribute (data- or otherwise) that you can search on:

 <div class="jtemplate" data-jtemplate-href="x"></div>
 <span class="jtemplate" data-jtemplate-text="x"></span>
 <input class="jtemplate" data-jtemplate-something="x"/>
 <table class="jtemplate" data-jtemplate-else="x"></table>

No need to define it as a CSS style. Now all you need is the selector $('.jtemplate') to get all those elements.

Upvotes: 3

Related Questions