Saurabh Agarwal
Saurabh Agarwal

Reputation: 527

Using gwtquery, how can we select elements with attributes having values containing more than one word?

Say I want to select an element such as

<div class="my class">InnerHTML</div>

While this may be done easily using CSS selectors with [class="my class"], gwtquery has a difference in the sense that it doesn't take the quotation marks in the input. It only accepts values like [attribute=attributevalue].

When I applied the same selector in GQuery with the space in between, it returned no matches. I have a feeling that this might be because of some incorrect parsing in the library for such cases. Is this so?

If so, is there any other way I might select these elements using GQuery?

Upvotes: 1

Views: 535

Answers (2)

BoltClock
BoltClock

Reputation: 723568

Generally, to select attributes with space-separated words, you'll use the [att~=val] selector as mentioned by Chris Lercher.

Or, you know, since you're selecting by the class attribute anyway, you could just use class selectors instead:

GQuery myClassDivs = $("div.my.class");

Regarding this:

When I applied the same selector in GQuery with the space in between, it returned no matches. I have a feeling that this might be because of some incorrect parsing in the library for such cases. Is this so?

If you're referring to adding the space in your unquoted attribute value, it's not a parsing error in the library. The selector itself is invalid because spaces in unquoted attribute values are explicitly invalid.

If quoted attribute values aren't recognized, then that is a parsing error in the library.

Upvotes: 1

Chris Lercher
Chris Lercher

Reputation: 37778

It works for me (at least with gwtquery-1.1.0 and gwt 2.4.0)

GQuery myClassDivs = $("div[class=\"my class\"]");

returns a match for <div class="my class"/>.


However, with the class attribute, it's generally better to use the ~= selector instead, because <div class="my class"/> and <div class="class my"/> should usually be treated as equivalent.

So I would suggest using

GQuery myClassDivs = $("div[class~=my][class~=class]");

This will also select something like <div class="my class special"/>, which is usually desirable.

Upvotes: 2

Related Questions