$
$ is the core function in ofa.js, used to get and manipulate DOM element instances. Below is a detailed introduction to the main features of $:
Obtaining Element Instances
With the $ method, you can retrieve the first element instance on the page that matches the CSS selector and perform operations on it. Here’s an example:
target 1 text
In the example above, we used the $ symbol to select the element instance with id "target1" and modified its text content by setting the text property.
Find Child Element Instance
Instances also have the $ method, which can be used to retrieve the first child element instance that meets the criteria from the instance.
target
I am target1
Do not insert the obtained element instance directly elsewhere, as this will affect the original element. If you need to create a copy, use the clone method.
position 1
I am target1
position 2
Get child elements within the shadow node
After obtaining the instance through the shadow attribute, you can use the $ method to get the desired element:
$('my-component').shadow.$("selector").method(xxx)
Instantiating Elements Directly
You can directly initialize a native element as a $ instance object in the following way:
const ele = document.createElement('div');
const $ele = $(ele);
const ele = document.querySelector('#target');
const $ele = $(ele);
This way, you can conveniently convert existing HTML elements into $ instances, enabling you to use the functionalities provided by $ for manipulation and processing.
Generate Element Instance
Besides, $ can be used not only to obtain existing element instances but also to create new ones and add them to the page.
Generate via String
You can create a new element instance from a string using the $ function, as shown below:
target1:
In this example, we use the $ function to create a new element instance with specified styles and text content, and add it inside an existing element instance with the id "target1".
Generate via object
You can also use the $ function to generate new element instances in an object-oriented manner, as shown below:
target1:
In this example, we use the $ function to define a new element instance in an object-oriented way, including the tag type, text content, and style attributes, and add it inside an existing element instance with an id of "target1".