Get the App
SLTechnology News&Howtos  ›  Development  › 

How to avoid repeated selections in jQuery

Shulou Source: shulou.com Published: 2022-06-01 04:51:06 10月03日 Update

This article is to share with you about how jQuery can avoid repeated choices. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Avoid repetitive selection

It is rare to reuse the same selector twice. The following code selects each p tag three times:

Css ("color", "blue"); $("p") .css ("font-size", "1.2em"); $("p") .text ("Text changed!")

Remember that jQuery supports chained operations; multiple methods can be applied to the same collection. Therefore, code with the same effect can be rewritten with a single selector:

("p") .css ({"color": "blue", "font-size": "1.2em"}) .text ("Text changed!")

If you need to use the same set of elements multiple times, you should cache the jQuery object with variables, such as:

Var $p = $("p"); $p.css ("color", "blue"); $p.text ("Text changed!")

Unlike standard DOM collections, jQuery collections are not real-time, and objects are not automatically updated when paragraph tags are added or removed from the document. You can take advantage of this limitation to create a DOM collection and pass it to the jQuery function as needed, such as:

Var p = document.getElementByTagName ("p"); $(p) .css ("color", "blue"); / / update the DOM$ (p) .text ("Text changed!"); Thank you for reading! This is the end of the article on "how to avoid repeated choices in jQuery". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Tags: Selection code content objects more tags articles different good practical elements functions variables can be passed multiple real-time effects documents articles methods Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Huawei Apple Shulou Technology MariaDB