How to grab form elements (with exception) by the selector?

Hi, I’d like to grab all elements inside the form except the last input. Anyone could help? The below selector doesn’t do the job. Say, there is no classes and the structure is like this one:

<form>
    <input>
    <span>
    <input>
</form>
form *:not(:last-of-type) {
    margin-right: 35px;
}

It might be easier to write a selector that affects every child of the form element and then another one that specifically targets the last input and overrides the style changes.

It’s a bit challenging as I don’t want to use classes. I’m not sure whether it’s possible at all. When I apply a class to form or to any other form parent element - that’s possible ; but as mentioned, let’s try not to use classes.

[X] form[.Y] > *:not(:last-of-type) {
    margin-right: 35px;
}

I’m not sure why you want to avoid classes. This is the sort of thing that classes are often used for. That said, my suggestion doesn’t rely on classes.

Here is a JSBin example where I have given all form children a style change, except for the last of a particular type.

since you’re selecting everything, would it be a :last-child instead of :last-of-type?

Yeah, that’s correct, however I still have to use classes - maybe there is a bug in my code somewhere or specificity conflict.

BTW - it’s not problem for my to use classes, just want to understand such behavior.

Depending on the complexity of your project, you may be able to do it without classes. The nice thing about using a class though is that you can change the structure of your HTML without having to rewrite complex selectors.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.