문제

I need a CSS selector that returns me the first element (or all of them in the correct order) by a specific set of values of the same attribute.

A bad example, but you'll get the idea:

input[type=text][type=email][type=number]:first

From this example HTML:

<input type="date" />
<input type="email" />
<input type="text" />
<input type="password" />

The selector must select <input type="email" /> or

<input type="email" />
<input type="text" />
<input type="password" />

It's ok to return all of them. But they must be in the original order. For example:

input[type=text], input[type=email], input[type=number]

Is not suitable as it selects elements in the wrong order. First all type=text, then type=email etc.

도움이 되었습니까?

해결책

In CSS you cannot get the first element inside a container based on a set of attributes, you can only do this with element types using nth-of-type. You can, however, set something like a required order and then pick in JS the first result available using the plus selector: http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#selectors

다른 팁

There is no first-match selector in CSS like jQuery's :first, so you won't be able to do this using pure CSS.

As mentioned in the comments, selectors themselves do not have a notion of order. You have a selector, and then you have all the elements in the DOM that would match that selector. In a comma-separated list of selectors, the ordering does not matter, except in CSS where the most specific of these selectors takes precedence for the purposes of cascade resolution (e.g. for an element that matches both selectors in input, input[type=email], the latter is considered in style resolution).

Using JavaScript, however, you can use document.querySelector() to pick out the first match, as it does have a notion of order:

document.querySelector('input[type=text], input[type=email], input[type=number]')

Note again that ordering does not matter in a selector list; in this case, it depends on the order of your elements in the DOM. In your example, assuming those are the only input elements of their kind in the entire DOM, or you have an appropriate scope from which to match elements, document.querySelector() will always match the input[type=email] first, even though it's specified after input[type=text] in the selector list, simply because it comes first in the DOM.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top