2

I'm data binding by adding a html5 data- custom attribute to an element

<div id="fred">
<input type="text" data-fld="Field1" value="10" />
<input type="text" data-fld="Field2" value="11" />
<input type="text" data-fld="Field3" value="12" />
<input type="text" value="13" />
</div>

I'm trying to search for all elements that have a data-fld specified.

col = div.find("[data-fld!='']");

But no luck with what I've tried this far.

Here's a jsfiddle for it. http://jsfiddle.net/p2KsP/4/

1 Answer 1

2

You only have to use a Has Attribute selector:

var col = $("#fred").find("[data-fld]");
console.log(col.length);  // 3

An Attribute Not Equal selector will not work because it matches elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value. It means [data-fld!=''] will end up matching all elements.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, yes that seems to work. Can you explain why !='' did not work ? Just interested and learning !
@user, that's because [data-fld!=''] does not do what you think it does. I tried to elaborate that point in my answer.

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.