Is There an Equivalent to Jquery's: First Selector in CSS3

Is there an equivalent to jQuery's :first selector in CSS3?

No, there is no equivalent CSS selector to jQuery's :first or :last selector, because those selectors are filters, and not true simple selectors by the CSS definition.

In Selectors 3 there is no :first-of-class or similar selector either.

However, you can use overriding rules with the ~ combinator to apply styles to the first child of a certain class:

  • CSS selector for first element with class
  • CSS selector to select first element of a given class

But there is currently no way to apply styles to the last child of a certain class using CSS:

  • Is it possible using current browsers to use pseudo-classes to detect first and last of a certain class?

CSS Selector for the first hit

The div.rc elements are all wrapped in div.g elements, which are siblings. So you can use:

div.g:first-child > div.rc

In jQuery you can use the :first extension.

$("#div.rc:first")

Is there a standard CSS selector similar to :eq() in jQuery?

While jQuery's :eq() uses 0-based indexing, :nth-child() uses 1-based indexing, so you need to increment your indexes appropriately:

.tab_cadre_central .top:nth-child(1) table tbody tr td table tbody tr:nth-child(4)

But you should really think about refactoring that selector...


⚠ It's worth noting that although :eq() and :nth-child() can behave similarly - they are certainly not the same. :eq() will select the n+1 th element in the set while :nth-child() will select all elements in the set that are the n th child of their respective parents. ⚠

<div>
<span></span>
<span></span>
</div>
<div>
<span></span>
</div>

The selector div span:nth-child(1) will fetch two elements, while div span:eq(0) will only select one.

When to use :first-child selector vs first() method in jQuery?

After a bit of research, I tried easy example myself and got the
difference.

$(document).ready(function(){    $(".first-child p:first-child").css("background-color", "yellow");    $(".first p").first().css("background-color", "yellow");});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h1>:first-child selector</h1>
<div class="first-child" style="border:1px solid black"> <p>This is a paragraph in a div.</p> <p>This is a paragraph in a div.</p></div><br><div class="first-child" style="border:1px solid black"> <p>This is another paragraph in a div.</p> <p>This is another paragraph in a div.</p></div><p>This is also a paragraph.</p><br>
<h1>first() method</h1>
<div class="first" style="border:1px solid black"> <p>This is a paragraph in a div.</p> <p>This is a paragraph in a div.</p></div><br><div class="first" style="border:1px solid black"> <p>This is another paragraph in a div.</p> <p>This is another paragraph in a div.</p></div>
<p>This is also a paragraph.</p><br>

Javascript equivalent to Jquerys :first / :last

jQuery's :first and :last give you the first or last matching element (element that matches the selector).

For :first, that's what querySelector gives you, so just:

firstInput =  document.querySelector('form#enquiry-form input[type="text"]:not(#first_name)');

There's no DOM equivalent of :last other than getting the list and grabbing the last entry from it:

const list = document.querySelectorAll('form#enquiry-form input[type="text"]:not(#first_name)');
lastInput = list.length ? list[list.length - 1] : null;

There's an at proposal making its way through the JavaScript process (it's at Stage 3, which is pretty far along). One can hope that it would be adopted by DOM collections as well (though I haven't heard that it will, but keep reading). If that happens, that code would get simpler:

// IF/WHEN `at` is adopted in DOM lists
lastInput = document.querySelectorAll('form#enquiry-form input[type="text"]:not(#first_name)').at(-1);

Or it may be that the NodeList and HTMLCollection interfaces start handling negative indexing via item (at was originally going to be item in hopes of unifying this aspect of arrays and DOM lists, but unfortunately that's not possible).

It's not clear at present whether either at or a negative index for item will necessarily be supported by DOM Lists. So you're probably best off having a utility function for it which you can hopefully update at some point.

Get exact selector in jQuery / alternative to .selector

In your example your use case is a static plugin example not a prototype plugin example. Using $.fn.myPlugin your asking the user of your plugin to manipulate it as it it was part of the jQuery API. In that case the plugin is designed to iterate over the jQuery object at that point in the call chain ($(this).each()).

However your example looks lke it acts on the actual jQuery object itself not on selected elements adn would be better served as a plugin on the jQuery class object:

$.yellowify = function (selector) {
var css = selector + "{color: yellow;}";
// I can add rules for specific elements now as well
css += selector + " .child {color: red;}";
$("<style>").html(css).appendTo("head");
});

It isn't entirely clear why you feel you want to do this. It's strange an alien. However, for completness plugins that act on the jQuery prototype chain need to loop over the already selected elements and return the original collection. If you need to look for elements within the selection then you would use .find().

Performance of jquery selectors vs css3 selectors

jQuery's selector engine shares most of the same syntax as CSS, effectively extending the selector standard. This means you can pass most valid CSS selectors (with some exceptions) to jQuery and it'll handle them just fine.

jQuery optimizes valid CSS selectors for modern browsers that support the selectors API by passing them directly to document.querySelectorAll(). This means your jQuery selector will have almost equal performance with the equivalent CSS selector, with the only overhead being the $().css() and the selectors API calls.

For browsers that don't support the selectors API, well, it's pretty obvious that jQuery will be really slow as it has to do all the heavy lifting on its own. More importantly, it will simply fail on the exceptions that I link to above as well as any other CSS selectors a browser doesn't support.

However, with all that said, jQuery will invariably be slower, as the browser has to run through a script and evaluate it before getting a chance to apply and compute your styles.

And after all this, honestly, it's not much even if you had hundreds of items — chances are the browser is going to take longer to fetch the markup than to render the styles. If you need to do styling, and CSS supports it, why not use CSS? That's why the language was created in the first place.

jQuery :first vs. .first()

.first() can be used to select the first element in a jQuery collection.

Basically, it avoids having to do a new query or break the chain in situations when you need to work on a collection and then exclusively on the first element.

Actually, one of the most costly operations you can do in jQuery is a query. The less you do, the better it is...

One example I can think of right now is an image gallery script where your first image is always the default active one, yet you need to attach an event handler on each image...

$('#gallery img').click(myFunc).first().addClass('active');

// Instead of
$('#gallery img').click(myFunc);
$('#gallery img:first').addClass('active');

.first() is also syntactic sugar for something that exists since 1.1.2... .eq(0):

$('#gallery img').click(myFunc).eq(0).addClass('active');

in fact, that's how it is implemented in jQuery itself:

first: function() {
return this.eq( 0 );
}

jQuery first of type selector?

Assuming you have a reference to the div already:

$(yourDiv).find("p").eq(0);

If the first p will always be a direct child of the div, you could use children instead of find.

Some alternatives include:

$(yourDiv).find("p:eq(0)"); //Slower than the `.eq` method
$(yourDiv).find("p:first");
$(yourDiv).find("p").first() //Just an alias for `.eq(0)`

Note that the eq method will always be the fastest way to do this. Here's the results of a quick comparison of the eq method, :eq selector and :first selector (I didn't bother with the first method since it's just an alias of eq(0)):

Sample Image



Related Topics



Leave a reply



Submit