CSS Selectors

 https://www.w3schools.com/cssref/css_selectors.php

In CSS, selectors are patterns used to select the element(s) you want to style.

Use our CSS Selector Tester to demonstrate the different selectors.

SelectorExampleExample description
.class.introSelects all elements with class="intro"
.class1.class2.name1.name2Selects all elements with both name1 and name2 set within its class attribute
.class1 .class2.name1 .name2Selects all elements with name2 that is a descendant of an element with name1
#id#firstnameSelects the element with id="firstname"
**Selects all elements
elementpSelects all <p> elements
element.classp.introSelects all <p> elements with class="intro"
element,elementdiv, pSelects all <div> elements and all <p> elements
element elementdiv pSelects all <p> elements inside <div> elements
element>elementdiv > pSelects all <p> elements where the parent is a <div> element
element+elementdiv + pSelects the first <p> element that is placed immediately after <div> elements
element1~element2p ~ ulSelects every <ul> element that is preceded by a <p> element
[attribute][target]Selects all elements with a target attribute
[attribute=value][target="_blank"]Selects all elements with target="_blank"
[attribute~=value][title~="flower"]Selects all elements with a title attribute containing the word "flower"
[attribute|=value][lang|="en"]Selects all elements with a lang attribute value equal to "en" or starting with "en-"
[attribute^=value]a[href^="https"]Selects every <a> element whose href attribute value begins with "https"
[attribute$=value]a[href$=".pdf"]Selects every <a> element whose href attribute value ends with ".pdf"
[attribute*=value]a[href*="w3schools"]Selects every <a> element whose href attribute value contains the substring "w3schools"
:activea:activeSelects the active link
::afterp::afterInsert something after the content of each <p> element
::beforep::beforeInsert something before the content of each <p> element
:checkedinput:checkedSelects every checked <input> element
:defaultinput:defaultSelects the default <input> element
:disabledinput:disabledSelects every disabled <input> element
:emptyp:emptySelects every <p> element that has no children (including text nodes)
:enabledinput:enabledSelects every enabled <input> element
:first-childp:first-childSelects every <p> element that is the first child of its parent
::first-letterp::first-letterSelects the first letter of every <p> element
::first-linep::first-lineSelects the first line of every <p> element
:first-of-typep:first-of-typeSelects every <p> element that is the first <p> element of its parent
:focusinput:focusSelects the input element which has focus
:fullscreen:fullscreenSelects the element that is in full-screen mode
:hovera:hoverSelects links on mouse over
:in-rangeinput:in-rangeSelects input elements with a value within a specified range
:indeterminateinput:indeterminateSelects input elements that are in an indeterminate state
:invalidinput:invalidSelects all input elements with an invalid value
:lang(language)p:lang(it)Selects every <p> element with a lang attribute equal to "it" (Italian)
:last-childp:last-childSelects every <p> element that is the last child of its parent
:last-of-typep:last-of-typeSelects every <p> element that is the last <p> element of its parent
:linka:linkSelects all unvisited links
::marker::markerSelects the markers of list items
:not(selector):not(p)Selects every element that is not a <p> element
:nth-child(n)p:nth-child(2)Selects every <p> element that is the second child of its parent
:nth-last-child(n)p:nth-last-child(2)Selects every <p> element that is the second child of its parent, counting from the last child
:nth-last-of-type(n)p:nth-last-of-type(2)Selects every <p> element that is the second <p> element of its parent, counting from the last child
:nth-of-type(n)p:nth-of-type(2)Selects every <p> element that is the second <p> element of its parent
:only-of-typep:only-of-typeSelects every <p> element that is the only <p> element of its parent
:only-childp:only-childSelects every <p> element that is the only child of its parent
:optionalinput:optionalSelects input elements with no "required" attribute
:out-of-rangeinput:out-of-rangeSelects input elements with a value outside a specified range
::placeholderinput::placeholderSelects input elements with the "placeholder" attribute specified
:read-onlyinput:read-onlySelects input elements with the "readonly" attribute specified
:read-writeinput:read-writeSelects input elements with the "readonly" attribute NOT specified
:requiredinput:requiredSelects input elements with the "required" attribute specified
:root:rootSelects the document's root element
::selection::selectionSelects the portion of an element that is selected by a user
:target#news:targetSelects the current active #news element (clicked on a URL containing that anchor name)
:validinput:validSelects all input elements with a valid value
:visiteda:visitedSelects all visited links

Implement error handling when using the Fetch API

 https://web.dev/articles/fetch-api-error-handling

Note that the following code examples use top-level await (browser support) because this feature can simplify your code.

This example uses a try/catch block statement to catch any errors thrown within the try block. For example, if the Fetch API cannot fetch the specified resource, then an error is thrown. Within a catch block like this, take care to provide a meaningful user experience. If a spinner, a common user interface that represents some sort of progress, is shown to the user, then you could take the following actions within a catch block:

  1. Remove the spinner from the page.
  2. Provide helpful messaging that explains what went wrong, and what options the user can take.
  3. Based on the available options, present a "Try again" button to the user.
  4. Behind the scenes, send the details of the error to your error-tracking service, or to the back-end. This action logs the error so it can be diagnosed at a later stage.
try {
 
const response = await fetch('https://website');
} catch (error) {
 
// TypeError: Failed to fetch
  console
.log('There was an error', error);
}

At a later stage, while you diagnose the error that you logged, you can write a test case to catch such an error before your users are aware something is wrong. Depending on the error, the test could be a unit, integration, or acceptance test.

This code example makes a request to an HTTP testing service that always responds with the HTTP status code 429 Too Many Requests. Interestingly, the response does not reach the catch block. A 404 status, amongst certain other status codes, does not return a network error but instead resolves normally.

To check that the HTTP status code was successful, you can use any of the following options:

  • Use the Response.ok property to determine whether the status code was in the range from 200 to 299.
  • Use the Response.status property to determine whether the response was successful.
  • Use any other metadata, such as Response.headers, to assess whether the response was successful.
try {
 
const response = await fetch('https://httpbin.org/status/429');
 
// network error in the 4xx–5xx range
 
if (!response.ok) {
   
throw new Error(`${response.status} ${response.statusText}`);
 
}
 
// use response here if we didn't throw above
  doSomethingWith
(response);
} catch (error) {
  console
.log(error);
}

The best practice is to work with people in your organization and team to understand potential HTTP response status codes. Backend developers, developer operations, and service engineers can sometimes provide unique insight into possible edge cases that you might not anticipate.

This code example demonstrates another type of error that can arise with parsing a response body. The Response interface offers convenient methods to parse different types of data, such as text or JSON. In the following code, a network request is made to an HTTP testing service that returns an HTML string as the response body. However, an attempt is made to parse the response body as JSON, throwing an error.

let json;

try {
 
const response = await fetch('https://httpbin.org/html');
  json
= await response.json();
} catch (error) {
 
if (error instanceof SyntaxError) {
   
// Unexpected token < in JSON
    console
.log('There was a SyntaxError', error);
 
} else {
    console
.log('There was an error', error);
 
}
}

if (json) {
  console
.log('Use the JSON here!', json);
}

You must prepare your code to take in a variety of response formats, and verify that an unexpected response doesn't break the web page for the user.

Consider the following scenario: You have a remote resource that returns a valid JSON response, and it is parsed successfully with the Response.json() method. It may happen that the service goes down. Once down, a 500 Internal Server Error is returned. If appropriate error-handling techniques are not used during the parsing of JSON, this could break the page for the user because an unhandled error is thrown.

This code example uses an AbortController to cancel an in-flight request. An in-flight request is a network request that has started but has not completed.

The scenarios where you may need to cancel an in-flight request can vary, but it ultimately depends on your use case and environment. The following code demonstrates how to pass an AbortSignal to the Fetch API. The AbortSignal is attached to an AbortController, and the AbortController includes an abort() method, which signifies to the browser that the network request should be canceled.

const controller = new AbortController();
const signal = controller.signal;

// Cancel the fetch request in 500ms
setTimeout
(() => controller.abort(), 500);

try {
 
const url = 'https://httpbin.org/delay/1';
 
const response = await fetch(url, { signal });
  console
.log(response);
} catch (error) {
 
// DOMException: The user aborted a request.
  console
.log('Error: ', error)
}

Is it okay to use both fetchpriority="high" and loading="eager" in img tag?

 https://stackoverflow.com/questions/77744344/is-it-okay-to-use-both-fetchpriority-high-and-loading-eager-in-img-tag Yes Fetchpriority and l...