mesdoc 0.2.1

An api to get ability to operate html document like jquery.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
use super::{BoxDynElement, IAttrValue, INodeType, InsertPosition, MaybeDoc, Texts};
use crate::utils::{get_class_list, retain_by_index, to_static_str};
use crate::{constants::ATTR_CLASS, error::Error as IError};
use crate::{
	constants::DEF_NODES_LEN,
	selector::{
		rule::{MatchAllHandle, MatchOneHandle},
		Combinator, QueryProcess, Selector, SelectorSegment,
	},
};
use std::collections::HashSet;
use std::{
	cmp::Ordering,
	collections::VecDeque,
	ops::{Bound, RangeBounds},
};
use std::{collections::HashMap, error::Error};

// get the ele indexs in tree
fn get_tree_indexs(ele: &BoxDynElement) -> VecDeque<usize> {
	let mut indexs: VecDeque<usize> = VecDeque::with_capacity(DEF_NODES_LEN);
	fn loop_handle(ele: &BoxDynElement, indexs: &mut VecDeque<usize>) {
		indexs.push_front(ele.index());
		if let Some(parent) = &ele.parent() {
			loop_handle(parent, indexs);
		}
	}
	loop_handle(ele, &mut indexs);
	indexs
}

// compare indexs
fn compare_indexs(a: &VecDeque<usize>, b: &VecDeque<usize>) -> Ordering {
	let a_total = a.len();
	let b_total = b.len();
	let loop_total = if a_total > b_total { b_total } else { a_total };
	for i in 0..loop_total {
		let a_index = a[i];
		let b_index = b[i];
		match a_index.cmp(&b_index) {
			Ordering::Equal => continue,
			order => return order,
		}
	}
	a_total.cmp(&b_total)
}

enum ElementRelation {
	Ancestor,
	Equal,
	Descendant,
	Feauture,
}
// check if ancestor and descendants
fn relation_of(a: &VecDeque<usize>, b: &VecDeque<usize>) -> ElementRelation {
	let a_total = a.len();
	let b_total = b.len();
	let loop_total = if a_total > b_total { b_total } else { a_total };
	let mut equal_num = 0;
	for i in 0..loop_total {
		let a_index = a[i];
		let b_index = b[i];
		match a_index.cmp(&b_index) {
			Ordering::Equal => {
				equal_num += 1;
				continue;
			}
			_ => break,
		}
	}
	let a_left = a_total - equal_num;
	let b_left = b_total - equal_num;
	match (a_left == 0, b_left == 0) {
		(false, false) => ElementRelation::Feauture,
		(false, true) => ElementRelation::Descendant,
		(true, true) => ElementRelation::Equal,
		(true, false) => ElementRelation::Ancestor,
	}
}

#[derive(Debug, PartialEq, Eq)]
pub(crate) enum FilterType {
	Filter,
	Not,
	Is,
	IsAll,
}

#[derive(Default)]
pub struct Elements<'a> {
	nodes: Vec<BoxDynElement<'a>>,
}

/*
*** Base methods
*/
impl<'a> Elements<'a> {
	/*-----------trigger method proxy---------------*/
	pub(crate) fn trigger_method<F, T: Default>(&self, method: &str, selector: &str, handle: F) -> T
	where
		F: Fn(&mut Selector) -> T,
	{
		if !self.is_empty() {
			// filter handles don't use lookup
			const USE_LOOKUP: bool = false;
			let s = Selector::from_str(selector, USE_LOOKUP);
			if let Ok(mut s) = s {
				return handle(&mut s);
			}
			self.trigger_method_throw_error(method, Box::new(s.unwrap_err()));
		}
		Default::default()
	}

	pub(crate) fn trigger_method_throw_error(&self, method: &str, error: Box<dyn Error>) {
		if let Some(doc) = &self
			.get(0)
			.expect("Use index 0 when length > 0")
			.owner_document()
		{
			doc.trigger_error(Box::new(IError::MethodOnInvalidSelector {
				method: String::from(method),
				error: error.to_string(),
			}));
		}
	}
	/*-----------create a elements----------------*/
	// new
	pub fn new() -> Self {
		Default::default()
	}
	// crate only methods
	pub(crate) fn with_node(ele: &BoxDynElement) -> Self {
		Elements {
			nodes: vec![ele.cloned()],
		}
	}
	// with nodes
	pub fn with_nodes(nodes: Vec<BoxDynElement<'a>>) -> Self {
		Elements { nodes }
	}

	// with capacity
	pub fn with_capacity(size: usize) -> Self {
		Elements {
			nodes: Vec::with_capacity(size),
		}
	}
	/*------------get/set element nodes---------------*/
	// get a element from the set
	pub fn get(&self, index: usize) -> Option<&BoxDynElement<'a>> {
		self.get_ref().get(index)
	}

	// get ref
	pub fn get_ref(&self) -> &Vec<BoxDynElement<'a>> {
		&self.nodes
	}

	// get mut ref
	pub(crate) fn get_mut_ref(&mut self) -> &mut Vec<BoxDynElement<'a>> {
		&mut self.nodes
	}
	// push node
	pub(crate) fn push(&mut self, ele: BoxDynElement<'a>) {
		self.get_mut_ref().push(ele);
	}
}

/*
*** Helper Methods
*/
impl<'a> Elements<'a> {
	// pub fn `for_each`
	pub fn for_each<F>(&mut self, mut handle: F) -> &mut Self
	where
		F: FnMut(usize, &mut BoxDynElement) -> bool,
	{
		for (index, ele) in self.get_mut_ref().iter_mut().enumerate() {
			if !handle(index, ele) {
				break;
			}
		}
		self
	}
	// alias for `for_each`
	pub fn each<F>(&mut self, handle: F) -> &mut Self
	where
		F: FnMut(usize, &mut BoxDynElement) -> bool,
	{
		self.for_each(handle)
	}
	// pub fn `map`
	pub fn map<F, T: Sized>(&self, handle: F) -> Vec<T>
	where
		F: Fn(usize, &BoxDynElement) -> T,
	{
		let mut result: Vec<T> = Vec::with_capacity(self.length());
		for (index, ele) in self.get_ref().iter().enumerate() {
			result.push(handle(index, ele));
		}
		result
	}

	/// pub fn `length`
	pub fn length(&self) -> usize {
		self.nodes.len()
	}
	/// pub fn `is_empty`
	pub fn is_empty(&self) -> bool {
		self.length() == 0
	}
	/// pub fn `document`, a quick way to get document
	pub fn document(&self) -> MaybeDoc {
		for ele in self.get_ref() {
			if let Some(doc) = ele.owner_document() {
				return Some(doc);
			}
		}
		None
	}
}

/*
*** Sort and Uniqueues
**  sort elements and unique elements
*/
impl<'a> Elements<'a> {
	// keep one sibling, first<asc:true> or last<asc:false>
	fn unique_sibling(&self, asc: bool) -> Elements<'a> {
		let total = self.length();
		let mut parents_indexs: HashSet<VecDeque<usize>> = HashSet::with_capacity(total);
		let mut uniques = Elements::with_capacity(total);
		let mut prev_parent: Option<BoxDynElement> = None;
		let mut has_root = false;
		let mut handle = |ele: &BoxDynElement| {
			if let Some(parent) = &ele.parent() {
				if let Some(prev_parent) = &prev_parent {
					if parent.is(prev_parent) {
						return;
					}
				}
				// set prev parent
				prev_parent = Some(parent.cloned());
				// parents
				let indexs = get_tree_indexs(parent);
				// new parent
				if parents_indexs.get(&indexs).is_none() {
					parents_indexs.insert(indexs);
					uniques.push(ele.cloned());
				}
			} else if !has_root {
				has_root = true;
				uniques.push(ele.cloned());
			}
		};
		// just keep one sibling node
		if asc {
			for ele in self.get_ref() {
				handle(ele);
			}
		} else {
			for ele in self.get_ref().iter().rev() {
				handle(ele)
			}
		}
		uniques
	}
	// keep first sibling
	fn unique_sibling_first(&self) -> Elements<'a> {
		self.unique_sibling(true)
	}
	// keep last sibling
	fn unique_sibling_last(&self) -> Elements<'a> {
		self.unique_sibling(false)
	}
	// keep siblings
	fn unique_all_siblings(&self) -> Vec<(BoxDynElement<'a>, bool)> {
		// should first unique siblings
		// if have two siblings, then use parent.children
		let total = self.length();
		let mut parents_indexs: HashMap<VecDeque<usize>, (usize, bool)> = HashMap::with_capacity(total);
		let mut uniques: Vec<(BoxDynElement, bool)> = Vec::with_capacity(total);
		let mut prev_parent: Option<BoxDynElement> = None;
		let mut continued = false;
		// just keep one sibling node
		for ele in self.get_ref() {
			if let Some(parent) = &ele.parent() {
				if let Some(prev_parent) = &prev_parent {
					if parent.is(prev_parent) {
						if !continued {
							// may first meet the sibling, set use all children
							if let Some(pair) = uniques.last_mut() {
								*pair = (parent.cloned(), true);
							}
							continued = true;
						}
						continue;
					}
				}
				// reset continued
				continued = false;
				// set prev parent
				prev_parent = Some(parent.cloned());
				// parent indexs
				let indexs = get_tree_indexs(parent);
				// new parent
				if let Some((index, setted)) = parents_indexs.get_mut(&indexs) {
					if !*setted {
						if let Some(pair) = uniques.get_mut(*index) {
							*pair = (parent.cloned(), true);
						}
						*setted = true;
					}
				} else {
					parents_indexs.insert(indexs, (uniques.len(), false));
					uniques.push((ele.cloned(), false));
				}
			}
		}
		uniques
	}
	// unique parent, keep the top parent
	fn unique_parents(&self) -> Elements<'a> {
		// keep only top parent
		let mut ancestors: Vec<(VecDeque<usize>, &BoxDynElement)> = Vec::with_capacity(self.length());
		for ele in self.get_ref() {
			let ele_indexs = get_tree_indexs(ele);
			let mut need_add = false;
			if !ancestors.is_empty() {
				let mut sub_indexs: Vec<usize> = Vec::new();
				for (index, (orig_ele_indexs, _)) in ancestors.iter().enumerate() {
					match relation_of(&ele_indexs, orig_ele_indexs) {
						ElementRelation::Feauture => {
							need_add = true;
							break;
						}
						ElementRelation::Ancestor => {
							// this feature should not hit, just keep the logic
							sub_indexs.push(index);
							need_add = true;
						}
						_ => break,
					}
				}
				// this will not trigger, just keep the logic
				if !sub_indexs.is_empty() {
					retain_by_index(&mut ancestors, &sub_indexs);
				}
			} else {
				need_add = true;
			}
			if need_add {
				ancestors.push((ele_indexs, ele));
			}
		}
		let mut result = Elements::with_capacity(ancestors.len());
		for (_, ele) in ancestors {
			result.push(ele.cloned());
		}
		result
	}
	// sort
	fn sort(&mut self) {
		self.get_mut_ref().sort_by(|a, b| {
			let a_index = get_tree_indexs(a);
			let b_index = get_tree_indexs(b);
			compare_indexs(&a_index, &b_index)
		});
	}
	// unique
	fn unique(&mut self) {
		self.get_mut_ref().dedup_by(|a, b| a.is(b));
	}
	// sort then unique
	fn sort_and_unique(&mut self) {
		self.sort();
		self.unique();
	}
}

/*
*** Selector APIs
**  [methods]
*/
impl<'a> Elements<'a> {
	// for all combinator selectors
	fn select_with_comb(&self, method: &str, selector: &str, comb: Combinator) -> Elements<'a> {
		if selector.is_empty() {
			let segment = Selector::make_comb_all(comb);
			let selector = Selector::from_segment(segment);
			return self.find_selector(&selector);
		}
		self.trigger_method(method, selector, |selector| {
			selector.head_combinator(comb);
			self.find_selector(&selector)
		})
	}
	// for all combinator until selectors
	fn select_with_comb_until(
		&self,
		method: &str,
		selector: &str,
		filter: &str,
		contains: bool,
		comb: Combinator,
	) -> Elements<'a> {
		let selector = selector.parse::<Selector>();
		if let Ok(selector) = &selector {
			let segment = Selector::make_comb_all(comb);
			let next_selector = Selector::from_segment(segment);
			let mut result = Elements::with_capacity(DEF_NODES_LEN);
			let (next_ok, filter) = if !filter.is_empty() {
				let filter = filter.parse::<Selector>();
				if let Ok(filter) = filter {
					(true, Some(filter))
				} else {
					self.trigger_method_throw_error(method, Box::new(filter.unwrap_err()));
					(false, None)
				}
			} else {
				(true, None)
			};
			if next_ok {
				// has filter
				for ele in self.get_ref() {
					let mut cur_eles = Elements::with_node(ele);
					loop {
						// find the next element
						cur_eles = cur_eles.find_selector(&next_selector);
						if !cur_eles.is_empty() {
							let meet_until = cur_eles.filter_type_handle(&selector, &FilterType::Is).1;
							// meet the until element, and not contains, stop before check element
							if meet_until && !contains {
								break;
							}
							// check if cur_eles filter
							let should_add = if let Some(filter) = &filter {
								// filter true
								cur_eles.filter_type_handle(filter, &FilterType::Is).1
							} else {
								// no need filter, just add
								true
							};
							if should_add {
								result.push(
									cur_eles
										.get(0)
										.expect("Elements get 0 must have when length > 0")
										.cloned(),
								);
							}
							// find the until, stop the loop at the end whenever contains or not
							if meet_until {
								break;
							}
						} else {
							break;
						}
					}
				}
				return result;
			}
		} else {
			self.trigger_method_throw_error(method, Box::new(selector.unwrap_err()));
		}
		Elements::new()
	}

	// prev
	pub fn prev(&self, selector: &str) -> Elements<'a> {
		self.select_with_comb("prev", selector, Combinator::Prev)
	}
	// prev_all
	pub fn prev_all(&self, selector: &str) -> Elements<'a> {
		let uniques = self.unique_sibling_last();
		uniques.select_with_comb("prev_all", selector, Combinator::PrevAll)
	}
	// prev_until
	pub fn prev_until(&self, selector: &str, filter: &str, contains: bool) -> Elements<'a> {
		let uniques = self.unique_sibling_last();
		uniques.select_with_comb_until("prev_until", selector, filter, contains, Combinator::Prev)
	}
	// next
	pub fn next(&self, selector: &str) -> Elements<'a> {
		self.select_with_comb("next", selector, Combinator::Next)
	}
	// next_all
	pub fn next_all(&self, selector: &str) -> Elements<'a> {
		// unique, keep the first sibling node
		let uniques = self.unique_sibling_first();
		uniques.select_with_comb("next_all", selector, Combinator::NextAll)
	}
	// next_until
	pub fn next_until(&self, selector: &str, filter: &str, contains: bool) -> Elements<'a> {
		// unique, keep the first sibling node
		let uniques = self.unique_sibling_first();
		uniques.select_with_comb_until("next_until", selector, filter, contains, Combinator::Next)
	}

	// siblings
	pub fn siblings(&self, selector: &str) -> Elements<'a> {
		let uniques = self.unique_all_siblings();
		// when selector is empty or only
		let mut siblings_selector: Selector;
		let siblings_comb = Combinator::Siblings;
		let mut child_selector: Selector;
		let child_comb = Combinator::Children;
		let selector = selector.trim();
		if selector.is_empty() {
			siblings_selector = Selector::from_segment(Selector::make_comb_all(siblings_comb));
			child_selector = Selector::from_segment(Selector::make_comb_all(child_comb));
		} else {
			// self
			let sib_selector = selector.parse::<Selector>();
			if let Ok(sib_selector) = sib_selector {
				// clone the selector to a child selector
				child_selector = selector
					.parse::<Selector>()
					.expect("The selector has detected");
				child_selector.head_combinator(child_comb);
				// use siblings selector
				siblings_selector = sib_selector;
				siblings_selector.head_combinator(siblings_comb);
			} else {
				self.trigger_method_throw_error(
					"siblings",
					Box::new(IError::InvalidTraitMethodCall {
						method: "siblings".to_string(),
						message: format!(
							"Invalid selector:{}",
							sib_selector.err().expect("Selector parse error")
						),
					}),
				);
				return Elements::new();
			}
		}
		// uniques
		let mut result = Elements::with_capacity(DEF_NODES_LEN);
		for (ele, is_parent) in &uniques {
			let eles = Elements::with_node(ele);
			let finded = if *is_parent {
				eles.find_selector(&child_selector)
			} else {
				eles.find_selector(&siblings_selector)
			};
			result.get_mut_ref().extend(finded);
		}
		// sort the result
		result.sort();
		result
	}
	// children
	pub fn children(&self, selector: &str) -> Elements<'a> {
		self.select_with_comb("children", selector, Combinator::Children)
	}

	// parent
	pub fn parent(&self, selector: &str) -> Elements<'a> {
		// unique, keep the first sibling node
		let uniques = self.unique_sibling_first();
		uniques.select_with_comb("parent", selector, Combinator::Parent)
	}
	// parents
	pub fn parents(&self, selector: &str) -> Elements<'a> {
		// unique, keep the first sibling node
		let uniques = self.unique_sibling_first();
		let mut result = uniques.select_with_comb("parents", selector, Combinator::ParentAll);
		result.sort_and_unique();
		result
	}
	// parents_until
	pub fn parents_until(&self, selector: &str, filter: &str, contains: bool) -> Elements<'a> {
		// unique, keep the first sibling node
		let uniques = self.unique_sibling_first();
		let mut result = uniques.select_with_comb_until(
			"parents_until",
			selector,
			filter,
			contains,
			Combinator::Parent,
		);
		result.sort_and_unique();
		result
	}
	// closest
	pub fn closest(&self, selector: &str) -> Elements<'a> {
		// when selector is not provided
		if selector.is_empty() {
			return Elements::new();
		}
		// find the nearst node
		const METHOD: &str = "closest";
		let selector = selector.parse::<Selector>();
		if let Ok(selector) = selector {
			let total = self.length();
			let mut result = Elements::with_capacity(total);
			let mut propagations = Elements::with_capacity(total);
			for ele in self.get_ref() {
				let mut cur_eles = Elements::with_node(ele);
				if cur_eles.filter_type_handle(&selector, &FilterType::Is).1 {
					// check self
					result.get_mut_ref().push(cur_eles.get_mut_ref().remove(0));
				} else {
					propagations
						.get_mut_ref()
						.push(cur_eles.get_mut_ref().remove(0));
				}
			}
			if !propagations.is_empty() {
				let uniques = propagations.unique_sibling_first();
				for ele in uniques.get_ref() {
					let mut cur_eles = Elements::with_node(ele);
					loop {
						if cur_eles.filter_type_handle(&selector, &FilterType::Is).1 {
							result.get_mut_ref().push(cur_eles.get_mut_ref().remove(0));
							break;
						}
						if let Some(parent) = &cur_eles
							.get(0)
							.expect("Elements must have one node")
							.parent()
						{
							cur_eles = Elements::with_node(parent);
						} else {
							break;
						}
					}
				}
				// need sort and unique
				result.sort_and_unique();
			}
			result
		} else {
			self.trigger_method_throw_error(METHOD, Box::new(selector.unwrap_err()));
			Elements::new()
		}
	}
	// for `find` and `select_with_comb`
	fn find_selector(&self, selector: &Selector) -> Elements<'a> {
		let mut result = Elements::with_capacity(DEF_NODES_LEN);
		if !self.is_empty() {
			for p in &selector.process {
				let QueryProcess { should_in, query } = p;
				let first_query = &query[0];
				let mut group: Option<Elements> = None;
				let mut start_rule_index: usize = 0;
				let mut is_empty = false;
				if let Some(lookup) = should_in {
					let mut cur_group = Elements::with_capacity(DEF_NODES_LEN);
					// get finded
					let finded = Elements::select(self, first_query, Some(&Combinator::ChildrenAll));
					if !finded.is_empty() {
						let tops = Elements::select(self, &lookup[0], None);
						if !tops.is_empty() {
							// remove the first
							start_rule_index = 1;
							// check if the previous ele and the current ele are siblings.
							let mut prev_ele: Option<&BoxDynElement> = None;
							let mut is_find = false;
							let first_comb = &first_query[0].1;
							for ele in finded.get_ref() {
								if prev_ele.is_some()
									&& Elements::is_sibling(ele, prev_ele.expect("Has test is_some"))
								{
									match first_comb {
										Combinator::Next => {
											if is_find {
												// do nothing, because has finded the only sibling ele matched.
												continue;
											}
											// if not find, should detect the current ele
										}
										Combinator::NextAll => {
											if is_find {
												cur_group.push(ele.cloned());
												continue;
											}
											// if not find, should detect the ele
										}
										_ => {
											// do the same thing as `prev_ele`
											// if `is_find` is true, then add the ele, otherwise it's not matched too.
											// keep the `is_find` value
											if is_find {
												cur_group.push(ele.cloned());
											}
											continue;
										}
									};
								}
								// check if the ele is in firsts
								if tops.has_ele(ele, &first_comb, Some(&lookup[1..])) {
									cur_group.push(ele.cloned());
									is_find = true;
								} else {
									is_find = false;
								}
								// set the prev ele
								prev_ele = Some(ele);
							}
						}
					}
					is_empty = cur_group.is_empty();
					group = Some(cur_group);
				}
				if !is_empty {
					let query = &query[start_rule_index..];
					if !query.is_empty() {
						let mut is_empty = false;
						let mut group = Elements::select(group.as_ref().unwrap_or(self), &query[0], None);

						for rules in &query[1..] {
							group = Elements::select(&group, rules, None);
							if group.is_empty() {
								is_empty = true;
								break;
							}
						}
						if !is_empty {
							result = result.add(group);
						}
					} else {
						let group = group.unwrap_or_else(|| self.cloned());
						if !group.is_empty() {
							result = result.add(group);
						}
					}
				}
			}
		}
		result
	}

	/// pub fn `find`
	/// get elements by selector, support most of css selectors
	pub fn find(&self, selector: &str) -> Elements<'a> {
		self.trigger_method("find", selector, |selector| self.find_selector(selector))
	}
	// select one rule
	// the rule must not in cache
	fn select_by_rule(
		elements: &Elements<'a>,
		rule_item: &SelectorSegment,
		comb: Option<&Combinator>,
	) -> Elements<'a> {
		let cur_comb = comb.unwrap_or(&rule_item.1);
		let (matcher, ..) = rule_item;
		let mut result = Elements::with_capacity(DEF_NODES_LEN);
		use Combinator::*;
		match cur_comb {
			ChildrenAll => {
				// unique if have ancestor and descendant relation elements
				let uniques = elements.unique_parents();
				// check if one handle, match one by one
				if let Some(handle) = &matcher.one_handle {
					let exec = |ele: &BoxDynElement, result: &mut Elements| {
						fn loop_handle(ele: &BoxDynElement, result: &mut Elements, handle: &MatchOneHandle) {
							let child_nodes = ele.child_nodes();
							for node in child_nodes {
								if matches!(node.node_type(), INodeType::Element) {
									let child_ele = node
										.typed()
										.into_element()
										.expect("Call typed for element node");
									let has_sub_child = child_ele.child_nodes_length() > 0;
									if has_sub_child {
										if handle(&child_ele, None) {
											result.get_mut_ref().push(child_ele.cloned());
										}
										loop_handle(&child_ele, result, handle);
									} else {
										// push the element
										if handle(&child_ele, None) {
											result.get_mut_ref().push(child_ele);
										}
									}
								}
							}
						}
						loop_handle(ele, result, handle)
					};
					// depth first search, keep the appear order
					for ele in uniques.get_ref() {
						exec(ele, &mut result);
					}
				} else {
					// if all handle, check all children
					let handle = matcher.get_all_handle();
					let exec = |ele: &BoxDynElement, result: &mut Elements| {
						// get children
						fn loop_handle(ele: &BoxDynElement, result: &mut Elements, handle: &MatchAllHandle) {
							let childs = ele.children();
							if !childs.is_empty() {
								// apply rule
								let matched_childs = handle(&childs, None);
								let matched_childs = matched_childs.get_ref();
								let total_matched = matched_childs.len();
								let mut cmp_index = 0;
								for child in childs.get_ref() {
									if cmp_index < total_matched {
										let cmp_child = &matched_childs[cmp_index];
										if child.is(&cmp_child) {
											cmp_index += 1;
											result.get_mut_ref().push(child.cloned());
										}
									}
									// loop for sub childs
									loop_handle(child, result, handle);
								}
							}
						}
						loop_handle(ele, result, handle)
					};
					// depth first search, keep the appear order
					for ele in uniques.get_ref() {
						exec(ele, &mut result);
					}
				};
			}
			Children => {
				// because elements is unique, so the children is unique too
				if let Some(handle) = &matcher.one_handle {
					for ele in elements.get_ref() {
						let child_nodes = ele.child_nodes();
						for node in child_nodes {
							if matches!(node.node_type(), INodeType::Element) {
								let child_ele = node
									.typed()
									.into_element()
									.expect("Call typed for element node");
								if handle(&child_ele, None) {
									result.get_mut_ref().push(child_ele);
								}
							}
						}
					}
				} else {
					let handle = matcher.get_all_handle();
					for ele in elements.get_ref() {
						let childs = ele.children();
						let match_childs = handle(&childs, None);
						if !match_childs.is_empty() {
							result.get_mut_ref().extend(match_childs);
						}
					}
				}
			}
			Parent => {
				// elements is unique, but may be siblings
				// so they maybe has equal parent, just keep only one
				let uniques = elements.unique_sibling_first();
				if let Some(handle) = &matcher.one_handle {
					for ele in uniques.get_ref() {
						if let Some(parent) = ele.parent() {
							if handle(&parent, None) {
								result.get_mut_ref().push(parent);
							}
						}
					}
				} else {
					let handle = matcher.get_all_handle();
					let mut parents = Elements::with_capacity(uniques.length());
					for ele in uniques.get_ref() {
						if let Some(parent) = ele.parent() {
							parents.push(parent);
						}
					}
					let matched_parents = handle(&parents, None);
					if !matched_parents.is_empty() {
						result.get_mut_ref().extend(matched_parents);
					}
				}
			}
			ParentAll => {
				if let Some(handle) = &matcher.one_handle {
					let exec = |ele: &BoxDynElement, result: &mut Elements| {
						fn loop_handle(ele: &BoxDynElement, result: &mut Elements, handle: &MatchOneHandle) {
							if let Some(parent) = ele.parent() {
								// try to find ancestor first
								// because ancestor appear early than parent, keep the order
								loop_handle(&parent, result, handle);
								// check parent
								if handle(&parent, None) {
									result.get_mut_ref().push(parent);
								}
							}
						}
						loop_handle(ele, result, handle);
					};
					// loop the elements
					for ele in elements.get_ref() {
						exec(ele, &mut result);
					}
					// maybe not unique, need sort and unique
					result.sort_and_unique();
				} else {
					// gather all parents
					fn loop_handle(ele: &BoxDynElement, parents: &mut Elements) {
						if let Some(parent) = ele.parent() {
							// add ancestor first
							loop_handle(&parent, parents);
							// add parent
							parents.push(parent);
						}
					}
					let mut all_parents = Elements::with_capacity(10);
					for ele in elements.get_ref() {
						loop_handle(ele, &mut all_parents);
					}
					// unique all parents;
					all_parents.sort_and_unique();
					// check if matched
					let handle = matcher.get_all_handle();
					let matched_parents = handle(&all_parents, None);
					if !matched_parents.is_empty() {
						result.get_mut_ref().extend(matched_parents);
					}
				}
			}
			NextAll => {
				// unique siblings just keep first
				let uniques = elements.unique_sibling_first();
				for ele in uniques.get_ref() {
					let nexts = ele.next_element_siblings();
					let matched_nexts = matcher.apply(&nexts, None);
					if !matched_nexts.is_empty() {
						result.get_mut_ref().extend(matched_nexts);
					}
				}
			}
			Next => {
				// because elements is unique, so the next is unique too
				let mut nexts = Elements::with_capacity(elements.length());
				if let Some(handle) = &matcher.one_handle {
					for ele in elements.get_ref() {
						if let Some(next) = ele.next_element_sibling() {
							if handle(&next, None) {
								nexts.push(next);
							}
						}
					}
					result = nexts;
				} else {
					for ele in elements.get_ref() {
						if let Some(next) = ele.next_element_sibling() {
							nexts.push(next);
						}
					}
					result = matcher.apply(&nexts, None);
				}
			}
			PrevAll => {
				// unique siblings just keep last
				let uniques = elements.unique_sibling_last();
				for ele in uniques.get_ref() {
					let nexts = ele.previous_element_siblings();
					result.get_mut_ref().extend(matcher.apply(&nexts, None));
				}
			}
			Prev => {
				// because elements is unique, so the prev is unique too
				let mut prevs = Elements::with_capacity(elements.length());
				if let Some(handle) = &matcher.one_handle {
					for ele in elements.get_ref() {
						if let Some(prev) = ele.previous_element_sibling() {
							if handle(&prev, None) {
								prevs.push(prev);
							}
						}
					}
					result = prevs;
				} else {
					for ele in elements.get_ref() {
						if let Some(prev) = ele.previous_element_sibling() {
							prevs.push(prev);
						}
					}
					result = matcher.apply(&prevs, None);
				}
			}
			Siblings => {
				// siblings
				if elements.length() > 1000 {
					// unique first
					let uniques = elements.unique_all_siblings();
					for (ele, is_parent) in uniques {
						let eles = if !is_parent {
							ele.siblings()
						} else {
							ele.children()
						};
						result.get_mut_ref().extend(matcher.apply(&eles, None));
					}
				} else {
					for ele in elements.get_ref() {
						let siblings = ele.siblings();
						result.get_mut_ref().extend(matcher.apply(&siblings, None));
					}
					// not unique, need sort and unique
					result.sort_and_unique();
				}
			}
			Chain => {
				// just filter
				result = matcher.apply(&elements, None);
			}
		};
		result
	}
	// select ele by rules
	fn select(
		elements: &Elements<'a>,
		rules: &[SelectorSegment],
		comb: Option<&Combinator>,
	) -> Elements<'a> {
		let first_rule = &rules[0];
		let comb = comb.unwrap_or(&first_rule.1);
		let mut elements = if first_rule.0.in_cache && matches!(comb, Combinator::ChildrenAll) {
			let (matcher, ..) = first_rule;
			// set use cache true
			let cached = matcher.apply(&elements, Some(true));
			let count = cached.length();
			if count > 0 {
				let mut result = Elements::with_capacity(count);
				for ele in cached.get_ref() {
					if elements.has_ele(ele, comb, None) {
						result.push(ele.cloned());
					}
				}
				result.sort_and_unique();
				result
			} else {
				Elements::new()
			}
		} else {
			Elements::select_by_rule(&elements, first_rule, Some(comb))
		};
		if !elements.is_empty() && rules.len() > 1 {
			for rule in &rules[1..] {
				elements = Elements::select_by_rule(&elements, rule, None);
				if elements.is_empty() {
					break;
				}
			}
		}
		elements
	}
	// cloned
	pub fn cloned(&self) -> Elements<'a> {
		let mut result = Elements::with_capacity(self.length());
		for ele in &self.nodes {
			result.push(ele.cloned());
		}
		result
	}
	// `has_ele`
	pub(crate) fn has_ele(
		&self,
		ele: &BoxDynElement,
		comb: &Combinator,
		lookup: Option<&[Vec<SelectorSegment>]>,
	) -> bool {
		let mut elements = Elements::with_node(ele);
		let mut lookup_comb = comb.reverse();
		if let Some(lookup) = lookup {
			for rules in lookup.iter().rev() {
				let finded = Elements::select(&elements, rules, Some(&lookup_comb));
				if finded.is_empty() {
					return false;
				}
				lookup_comb = rules[0].1.reverse();
				elements = finded;
			}
		}
		use Combinator::*;
		match lookup_comb {
			Parent => {
				for ele in elements.get_ref() {
					if let Some(parent) = &ele.parent() {
						if self.includes(&parent) {
							return true;
						}
					}
				}
			}
			ParentAll => {
				for ele in elements.get_ref() {
					if let Some(parent) = &ele.parent() {
						if self.includes(&parent) {
							return true;
						}
						if let Some(ancestor) = &parent.parent() {
							if self.includes(&ancestor) {
								return true;
							}
							if self.has_ele(&ancestor, comb, None) {
								return true;
							}
						}
					}
				}
			}
			Prev => {
				for ele in elements.get_ref() {
					if let Some(prev) = &ele.previous_element_sibling() {
						if self.includes(&prev) {
							return true;
						}
					}
				}
			}
			PrevAll => {
				for ele in elements.get_ref() {
					let prevs = ele.previous_element_siblings();
					for prev in prevs.get_ref() {
						if self.includes(prev) {
							return true;
						}
					}
				}
			}
			Chain => {
				for ele in elements.get_ref() {
					if self.includes(ele) {
						return true;
					}
				}
			}
			_ => panic!("Unsupported lookup combinator:{:?}", comb),
		};
		false
	}
	// filter_type_handle:
	// type     | rule processes
	// ----------------------------------------
	// Filter   | merge all elmements which matched each process
	// Not      | merge all elmements which matched each process, then exclude them all.
	// Is       | once matched a process, break
	// IsAll    | merge all elmements which matched each process, check if the matched equal to self
	pub(crate) fn filter_type_handle(
		&self,
		selector: &Selector,
		filter_type: &FilterType,
	) -> (Elements<'a>, bool) {
		let eles = self.get_ref();
		let total = eles.len();
		let mut result = Elements::with_capacity(total);
		let mut all_matched = false;
		let chain_comb = Combinator::Chain;
		let mut root: Option<Elements> = None;
		for process in selector.process.iter() {
			// filter methods make sure do not use `should_in`
			let QueryProcess { query, .. } = process;
			let query_num = query.len();
			let mut filtered = Elements::new();
			if query_num > 0 {
				let last_query = &query[query_num - 1];
				let last_query_first_rule = &last_query[0];
				filtered =
					Elements::select_by_rule(self, last_query_first_rule, Some(&chain_comb)).cloned();
				if !filtered.is_empty() && last_query.len() > 1 {
					for rule in &last_query[1..] {
						filtered = Elements::select_by_rule(&filtered, rule, None);
						if filtered.is_empty() {
							break;
						}
					}
				}
				if !filtered.is_empty() && query_num > 1 {
					// set root first
					root = root.or_else(|| {
						let root_element = filtered
							.get(0)
							.expect("Filtered length greater than 0")
							.root();
						Some(Elements::with_node(&root_element))
					});
					// get root elements
					let root_eles = root.as_ref().expect("root element must have");
					// find elements from root_eles by selector
					let lookup = Some(&query[..query_num - 1]);
					let mut lasts = Elements::with_capacity(filtered.length());
					let comb = &last_query_first_rule.1;
					for ele in filtered.get_ref() {
						if root_eles.has_ele(ele, comb, lookup) {
							lasts.get_mut_ref().push(ele.cloned());
						}
					}
					filtered = lasts;
				}
			}
			if !filtered.is_empty() {
				match filter_type {
					FilterType::Is => {
						all_matched = true;
						break;
					}
					_ => {
						result = result.add(filtered);
					}
				}
			}
		}
		match filter_type {
			FilterType::IsAll => {
				all_matched = result.length() == total;
			}
			FilterType::Not => {
				// Exclude `filtered` from self
				if result.is_empty() {
					// no element matched the not selector
					result = self.cloned();
				} else {
					// filtered by not in
					result = self.not_in(&result);
				}
			}
			_ => {
				// FilterType::Is: just return 'all_matched'
				// FilterType::Filter: just return 'result'
			}
		}
		(result, all_matched)
	}

	// filter in type
	fn filter_in_handle(&self, search: &Elements, filter_type: FilterType) -> (Elements<'a>, bool) {
		let eles = self.get_ref();
		let total = eles.len();
		let mut result = Elements::with_capacity(total);
		let mut all_matched = false;
		match filter_type {
			FilterType::Filter => {
				let mut start_index = 0;
				let search_total = search.length();
				for ele in eles {
					if let Some(index) = search.index_of(ele, start_index) {
						// also in search, include
						start_index = index + 1;
						result.push(ele.cloned());
						if start_index >= search_total {
							break;
						}
					}
				}
			}
			FilterType::Not => {
				let mut start_index = 0;
				for ele in eles {
					if let Some(index) = search.index_of(ele, start_index) {
						// also in search, exclude
						start_index = index + 1;
					} else {
						result.push(ele.cloned());
					}
				}
			}
			FilterType::Is => {
				for ele in eles {
					if search.includes(ele) {
						all_matched = true;
						break;
					}
				}
			}
			FilterType::IsAll => {
				if total <= search.length() {
					let mut is_all_matched = true;
					let mut start_index = 0;
					for ele in eles {
						if let Some(index) = search.index_of(ele, start_index) {
							// also in search, exclude
							start_index = index + 1;
						} else {
							is_all_matched = false;
							break;
						}
					}
					all_matched = is_all_matched;
				}
			}
		}
		(result, all_matched)
	}

	// filter
	pub fn filter(&self, selector: &str) -> Elements<'a> {
		const METHOD: &str = "filter";
		self.trigger_method(METHOD, selector, |selector| {
			self.filter_type_handle(&selector, &FilterType::Filter).0
		})
	}

	// filter_by
	pub fn filter_by<F>(&self, handle: F) -> Elements<'a>
	where
		F: Fn(usize, &BoxDynElement) -> bool,
	{
		let mut result = Elements::with_capacity(self.length());
		for (index, ele) in self.get_ref().iter().enumerate() {
			if handle(index, ele) {
				// find the ele, allow cloned
				result.push(ele.cloned());
			}
		}
		result
	}

	// filter in
	pub fn filter_in(&self, search: &Elements) -> Elements<'a> {
		self.filter_in_handle(search, FilterType::Filter).0
	}

	// is
	pub fn is(&self, selector: &str) -> bool {
		const METHOD: &str = "is";
		self.trigger_method(METHOD, selector, |selector| {
			self.filter_type_handle(selector, &FilterType::Is).1
		})
	}

	// is by
	pub fn is_by<F>(&self, handle: F) -> bool
	where
		F: Fn(usize, &BoxDynElement) -> bool,
	{
		let mut flag = false;
		for (index, ele) in self.get_ref().iter().enumerate() {
			if handle(index, ele) {
				flag = true;
				break;
			}
		}
		flag
	}

	// is in
	pub fn is_in(&self, search: &Elements) -> bool {
		self.filter_in_handle(search, FilterType::Is).1
	}

	// is_all
	pub fn is_all(&self, selector: &str) -> bool {
		const METHOD: &str = "is_all";
		self.trigger_method(METHOD, selector, |selector| {
			self.filter_type_handle(&selector, &FilterType::IsAll).1
		})
	}

	// is_all_by
	pub fn is_all_by<F>(&self, handle: F) -> bool
	where
		F: Fn(usize, &BoxDynElement) -> bool,
	{
		let mut flag = true;
		for (index, ele) in self.get_ref().iter().enumerate() {
			if !handle(index, ele) {
				flag = false;
				break;
			}
		}
		flag
	}

	// is_all_in
	pub fn is_all_in(&self, search: &Elements) -> bool {
		self.filter_in_handle(search, FilterType::IsAll).1
	}

	// not
	pub fn not(&self, selector: &str) -> Elements<'a> {
		const METHOD: &str = "not";
		self.trigger_method(METHOD, selector, |selector| {
			self.filter_type_handle(&selector, &FilterType::Not).0
		})
	}

	// not by
	pub fn not_by<F>(&self, handle: F) -> Elements<'a>
	where
		F: Fn(usize, &BoxDynElement) -> bool,
	{
		let mut result = Elements::with_capacity(self.length());
		for (index, ele) in self.get_ref().iter().enumerate() {
			if !handle(index, ele) {
				result.push(ele.cloned());
			}
		}
		result
	}

	/// pub fn `not_in`
	/// remove element from `Self` which is also in `search`
	pub fn not_in(&self, search: &Elements) -> Elements<'a> {
		self.filter_in_handle(search, FilterType::Not).0
	}

	// has
	pub fn has(&self, selector: &str) -> Elements<'a> {
		const METHOD: &str = "has";
		fn loop_handle(ele: &BoxDynElement, selector: &Selector) -> bool {
			let childs = ele.children();
			if !childs.is_empty() {
				let (_, all_matched) = childs.filter_type_handle(selector, &FilterType::Is);
				if all_matched {
					return true;
				}
				for child in childs.get_ref() {
					if loop_handle(child, selector) {
						return true;
					}
				}
			}
			false
		}
		self.trigger_method(METHOD, selector, |selector| {
			self.filter_by(|_, ele| loop_handle(ele, selector))
		})
	}

	// has_in
	pub fn has_in(&self, search: &Elements) -> Elements<'a> {
		fn loop_handle(ele: &BoxDynElement, search: &Elements) -> bool {
			let childs = ele.children();
			if !childs.is_empty() {
				let (_, all_matched) = childs.filter_in_handle(search, FilterType::Is);
				if all_matched {
					return true;
				}
				for child in childs.get_ref() {
					if loop_handle(child, search) {
						return true;
					}
				}
			}
			false
		}
		self.filter_by(|_, ele| loop_handle(ele, &search))
	}
}

/*
*** Other Selector and Helper APIs
**  [Methods]
*/
impl<'a> Elements<'a> {
	/// pub fn `eq`
	/// get a element by index
	pub fn eq(&self, index: usize) -> Elements<'a> {
		if let Some(ele) = self.get(index) {
			Elements::with_node(ele)
		} else {
			Elements::new()
		}
	}

	/// pub fn `first`
	/// get the first element, alias for 'eq(0)'
	pub fn first(&self) -> Elements<'a> {
		self.eq(0)
	}

	/// pub fn `last`
	/// get the last element, alias for 'eq(len - 1)'
	pub fn last(&self) -> Elements<'a> {
		self.eq(self.length() - 1)
	}

	/// pub fn `slice`
	/// get elements by a range parameter
	/// `slice(0..1)` equal to `eq(0)`, `first`
	pub fn slice<T: RangeBounds<usize>>(&self, range: T) -> Elements<'a> {
		let mut start = 0;
		let mut end = self.length();
		match range.start_bound() {
			Bound::Unbounded => {
				// start = 0
			}
			Bound::Included(&cur_start) => {
				if cur_start < end {
					start = cur_start;
				} else {
					// empty
					return Elements::new();
				}
			}
			_ => {
				// start bound not have exclude
			}
		};
		match range.end_bound() {
			Bound::Unbounded => {
				// end = total
			}
			Bound::Excluded(&cur_end) => {
				if cur_end < end {
					end = cur_end;
				}
			}
			Bound::Included(&cur_end) => {
				let cur_end = cur_end + 1;
				if cur_end < end {
					end = cur_end;
				}
			}
		}
		let mut result = Elements::with_capacity(end - start);
		let eles = self.get_ref();
		for ele in &eles[start..end] {
			result.push(ele.cloned());
		}
		result
	}

	/// pub fn `add`
	/// concat two element set to a new set,
	/// it will take the owership of the parameter element set, but no sence to `Self`
	pub fn add(&self, eles: Elements<'a>) -> Elements<'a> {
		if self.is_empty() {
			return eles;
		}
		if eles.is_empty() {
			return self.cloned();
		}
		let first_eles = self;
		let second_eles = &eles;
		// compare first and second
		let first_count = first_eles.length();
		let second_count = second_eles.length();
		let avg = second_count / 3;
		let mut prevs: Vec<usize> = Vec::with_capacity(avg);
		let mut mids: Vec<(usize, usize)> = Vec::with_capacity(avg);
		let mut afters: Vec<usize> = Vec::with_capacity(avg);
		let mut sec_left_index = 0;
		let sec_right_index = second_count - 1;
		let mut first_indexs: HashMap<usize, VecDeque<usize>> = HashMap::with_capacity(first_count);
		let mut fir_left_index = 0;
		let fir_right_index = first_count - 1;
		let first = first_eles.get_ref();
		let second = second_eles.get_ref();
		// get first index cached or from cached
		fn get_first_index_cached<'a>(
			first_indexs: &'a mut HashMap<usize, VecDeque<usize>>,
			first: &[BoxDynElement],
			index: usize,
		) -> &'a mut VecDeque<usize> {
			first_indexs
				.entry(index)
				.or_insert_with(|| get_tree_indexs(&first[index]))
		};
		while fir_left_index <= fir_right_index && sec_left_index <= sec_right_index {
			// the second left
			let sec_left = &second[sec_left_index];
			let sec_left_level = get_tree_indexs(sec_left);
			// the first left
			let fir_left_level = get_first_index_cached(&mut first_indexs, &first, fir_left_index);
			match compare_indexs(&sec_left_level, &fir_left_level) {
				Ordering::Equal => {
					// move forward both
					sec_left_index += 1;
					fir_left_index += 1;
				}
				Ordering::Greater => {
					// second left is behind first left
					// if second left is also behind first right
					let fir_right_level = get_first_index_cached(&mut first_indexs, &first, fir_right_index);
					match compare_indexs(&sec_left_level, &fir_right_level) {
						Ordering::Greater => {
							// now second is all after first
							afters.extend(sec_left_index..=sec_right_index);
							break;
						}
						Ordering::Less => {
							// second left is between first left and right
							// use binary search
							let mut l = fir_left_index;
							let mut r = fir_right_index;
							let mut mid = (l + r) / 2;
							let mut find_equal = false;
							while mid != l {
								let mid_level = get_first_index_cached(&mut first_indexs, &first, mid);
								match compare_indexs(&sec_left_level, &mid_level) {
									Ordering::Greater => {
										// second left is behind middle
										l = mid;
										mid = (l + r) / 2;
									}
									Ordering::Less => {
										// second left is before middle
										r = mid;
										mid = (l + r) / 2;
									}
									Ordering::Equal => {
										// find equal
										find_equal = true;
										break;
									}
								}
							}
							if !find_equal {
								mids.push((sec_left_index, mid + 1));
							}
							// set first left from mid
							fir_left_index = mid;
							// move second left index
							sec_left_index += 1;
						}
						Ordering::Equal => {
							// equal to first right, now all the second after current is behind first
							afters.extend(sec_left_index + 1..=sec_right_index);
							break;
						}
					}
				}
				Ordering::Less => {
					let sec_right = &second[sec_right_index];
					let sec_right_level = get_tree_indexs(sec_right);
					match compare_indexs(&sec_right_level, &fir_left_level) {
						Ordering::Less => {
							// now second is all before first
							prevs.extend(sec_left_index..=sec_right_index);
							break;
						}
						Ordering::Greater => {
							// second contains first or second right is in first
							// just move second left
							prevs.push(sec_left_index);
							sec_left_index += 1;
						}
						Ordering::Equal => {
							// equal to first left, now all the second are before first left
							prevs.extend(sec_left_index..sec_right_index);
							break;
						}
					}
				}
			}
		}
		let prevs_count = prevs.len();
		let mids_count = mids.len();
		let afters_count = afters.len();
		let mut result = Elements::with_capacity(first_count + prevs_count + mids_count + afters_count);
		if prevs_count > 0 {
			// add prevs
			for index in prevs {
				let ele = &second[index];
				result.push(ele.cloned());
			}
		}
		// add first and mids
		let mut mid_loop = 0;
		for (index, ele) in first_eles.get_ref().iter().enumerate() {
			if mid_loop < mids_count {
				let cur_mids = &mids[mid_loop..];
				// maybe multiple middles is between first left and right
				for (sec_index, mid_index) in cur_mids {
					if *mid_index == index {
						mid_loop += 1;
						let mid_ele = &second[*sec_index];
						result.push(mid_ele.cloned());
					} else {
						break;
					}
				}
			}
			result.push(ele.cloned());
		}
		// add afters
		if afters_count > 0 {
			// add afters
			for index in afters {
				let ele = &second[index];
				result.push(ele.cloned());
			}
		}
		result
	}

	/// check if the ele list contains some ele
	fn includes(&self, ele: &BoxDynElement) -> bool {
		self.get_ref().iter().any(|n| ele.is(n))
	}

	/// index of
	fn index_of(&self, ele: &BoxDynElement, start_index: usize) -> Option<usize> {
		let total = self.length();
		if start_index < total {
			let nodes = self.get_ref();
			for (index, cur_ele) in nodes[start_index..].iter().enumerate() {
				if ele.is(cur_ele) {
					return Some(start_index + index);
				}
			}
		}
		None
	}

	/// check if two nodes are siblings.
	fn is_sibling(cur: &BoxDynElement, other: &BoxDynElement) -> bool {
		// just check if they have same parent.
		if let Some(parent) = cur.parent() {
			if let Some(other_parent) = other.parent() {
				return parent.is(&other_parent);
			}
		}
		false
	}
}

/*
*** Content APIs
**  [Methods]
**  text, html, set_text, set_html, texts
*/
impl<'a> Elements<'a> {
	// -------------Content API----------------
	/// pub fn `text`
	/// get the text of each element in the set
	pub fn text(&self) -> &str {
		let mut result = String::with_capacity(50);
		for ele in self.get_ref() {
			result.push_str(ele.text_content());
		}
		to_static_str(result)
	}

	/// pub fn `set_text`
	/// set each element's text to content
	pub fn set_text(&mut self, content: &str) -> &mut Self {
		for ele in self.get_mut_ref() {
			ele.set_text(content);
		}
		self
	}

	/// pub fn `html`
	/// get the first element's html
	pub fn html(&self) -> &str {
		if let Some(ele) = self.get(0) {
			return ele.inner_html();
		}
		""
	}

	/// pub fn `set_html`
	/// set each element's html to content
	pub fn set_html(&mut self, content: &str) -> &mut Self {
		for ele in self.get_mut_ref() {
			ele.set_html(content);
		}
		self
	}

	/// pub fn `outer_html`
	/// get the first element's outer html
	pub fn outer_html(&self) -> &str {
		if let Some(ele) = self.get(0) {
			return ele.outer_html();
		}
		""
	}

	/// pub fn `texts`
	/// get the text node of each element
	pub fn texts(&self, limit_depth: u32) -> Texts<'a> {
		let mut result = Texts::with_capacity(DEF_NODES_LEN);
		for ele in self.get_ref() {
			if let Some(text_nodes) = ele.texts(limit_depth) {
				result.get_mut_ref().extend(text_nodes);
			}
		}
		result
	}
}

/*
*** Attribute APIs
**  [Methods]
**  attr, set_attr, remove_attr,
**  has_class, add_class, remove_class, toggle_class
*/
impl<'a> Elements<'a> {
	/// pub fn `attr`
	/// get the first element's attribute value
	pub fn attr(&self, attr_name: &str) -> Option<IAttrValue> {
		if let Some(ele) = self.get(0) {
			return ele.get_attribute(attr_name);
		}
		None
	}

	/// pub fn `set_attr`
	/// set each element's attribute to `key` = attr_name, `value` = value.  
	pub fn set_attr(&mut self, attr_name: &str, value: Option<&str>) -> &mut Self {
		for ele in self.get_mut_ref() {
			ele.set_attribute(attr_name, value);
		}
		self
	}

	/// pub fn `remove_attr`
	pub fn remove_attr(&mut self, attr_name: &str) -> &mut Self {
		for ele in self.get_mut_ref() {
			ele.remove_attribute(attr_name);
		}
		self
	}

	/// pub fn `has_class`
	pub fn has_class(&self, class_name: &str) -> bool {
		let class_name = class_name.trim();
		if !class_name.is_empty() {
			let class_list = get_class_list(class_name);
			for ele in self.get_ref() {
				let class_value = ele.get_attribute(ATTR_CLASS);
				if let Some(IAttrValue::Value(cls, _)) = class_value {
					let orig_class_list = get_class_list(&cls);
					for class_name in &class_list {
						// if any of element contains the class
						if orig_class_list.contains(class_name) {
							return true;
						}
					}
				}
			}
		}
		false
	}

	/// pub fn `add_class`
	pub fn add_class(&mut self, class_name: &str) -> &mut Self {
		let class_name = class_name.trim();
		if !class_name.is_empty() {
			let class_list = get_class_list(class_name);
			for ele in self.get_mut_ref() {
				let class_value = ele.get_attribute(ATTR_CLASS);
				if let Some(IAttrValue::Value(cls, _)) = class_value {
					let mut orig_class_list = get_class_list(&cls);
					for class_name in &class_list {
						if !orig_class_list.contains(class_name) {
							orig_class_list.push(class_name);
						}
					}
					ele.set_attribute(ATTR_CLASS, Some(orig_class_list.join(" ").as_str()));
					continue;
				}
				ele.set_attribute(ATTR_CLASS, Some(class_name));
			}
		}
		self
	}
	/// pub fn `remove_class`
	pub fn remove_class(&mut self, class_name: &str) -> &mut Self {
		let class_name = class_name.trim();
		if !class_name.is_empty() {
			let class_list = get_class_list(class_name);
			for ele in self.get_mut_ref() {
				let class_value = ele.get_attribute(ATTR_CLASS);
				if let Some(IAttrValue::Value(cls, _)) = class_value {
					let mut orig_class_list = get_class_list(&cls);
					let mut removed_indexs: Vec<usize> = Vec::with_capacity(class_list.len());
					for class_name in &class_list {
						if let Some(index) = orig_class_list.iter().position(|name| name == class_name) {
							removed_indexs.push(index);
						}
					}
					if !removed_indexs.is_empty() {
						retain_by_index(&mut orig_class_list, &removed_indexs);
						ele.set_attribute(ATTR_CLASS, Some(orig_class_list.join(" ").as_str()));
					}
				}
			}
		}
		self
	}
	/// pub fn `toggle_class`
	pub fn toggle_class(&mut self, class_name: &str) -> &mut Self {
		let class_name = class_name.trim();
		if !class_name.is_empty() {
			let class_list = get_class_list(class_name);
			let total = class_list.len();
			for ele in self.get_mut_ref() {
				let class_value = ele.get_attribute(ATTR_CLASS);
				if let Some(IAttrValue::Value(cls, _)) = class_value {
					let mut orig_class_list = get_class_list(&cls);
					let mut removed_indexs: Vec<usize> = Vec::with_capacity(total);
					let mut added_class_list: Vec<&str> = Vec::with_capacity(total);
					for class_name in &class_list {
						if let Some(index) = orig_class_list.iter().position(|name| name == class_name) {
							removed_indexs.push(index);
						} else {
							added_class_list.push(class_name);
						}
					}
					let mut need_set = false;
					if !removed_indexs.is_empty() {
						retain_by_index(&mut orig_class_list, &removed_indexs);
						need_set = true;
					}
					if !added_class_list.is_empty() {
						orig_class_list.extend(added_class_list);
						need_set = true;
					}
					if need_set {
						ele.set_attribute(ATTR_CLASS, Some(orig_class_list.join(" ").as_str()));
					}
					continue;
				}
				ele.set_attribute(ATTR_CLASS, Some(class_name));
			}
		}
		self
	}
}

/*
*** Mutations
**  [methods]
**  remove, empty,
**  append, append_to, prepend, prepend_to,
**  before, insert_before, after, insert_after
*/
impl<'a> Elements<'a> {
	/// pub fn `remove`
	pub fn remove(self) {
		for ele in self.into_iter() {
			if let Some(parent) = ele.parent().as_mut() {
				parent.remove_child(ele);
			}
		}
	}
	// pub fn `empty`
	pub fn empty(&mut self) -> &mut Self {
		self.set_text("");
		self
	}
	// `insert`
	fn insert(&mut self, dest: &Elements, position: &InsertPosition) -> &mut Self {
		for ele in self.get_mut_ref() {
			for inserted in dest.get_ref().iter().rev() {
				ele.insert_adjacent(position, inserted);
			}
		}
		self
	}
	/// pub fn `append`
	pub fn append(&mut self, elements: &mut Elements) -> &mut Self {
		self.insert(elements, &InsertPosition::BeforeEnd);
		self
	}
	/// pub fn `append_to`
	pub fn append_to(&mut self, elements: &mut Elements) -> &mut Self {
		elements.append(self);
		self
	}
	/// pub fn `prepend`
	pub fn prepend(&mut self, elements: &mut Elements) -> &mut Self {
		self.insert(elements, &InsertPosition::AfterBegin);
		self
	}
	/// pub fn `prepend_to`
	pub fn prepend_to(&mut self, elements: &mut Elements) -> &mut Self {
		elements.prepend(self);
		self
	}
	/// pub fn `insert_before`
	pub fn insert_before(&mut self, elements: &mut Elements) -> &mut Self {
		elements.before(self);
		self
	}
	/// pub fn `before`
	pub fn before(&mut self, elements: &mut Elements) -> &mut Self {
		// insert the elements before self
		self.insert(elements, &InsertPosition::BeforeBegin);
		self
	}
	/// pub fn `insert_after`
	pub fn insert_after(&mut self, elements: &mut Elements) -> &mut Self {
		elements.after(self);
		self
	}
	/// pub fn `after`
	pub fn after(&mut self, elements: &mut Elements) -> &mut Self {
		// insert the elements after self
		self.insert(elements, &InsertPosition::AfterEnd);
		self
	}
}

impl<'a> IntoIterator for Elements<'a> {
	type Item = BoxDynElement<'a>;
	type IntoIter = Box<dyn Iterator<Item = Self::Item> + 'a>;
	fn into_iter(self) -> Self::IntoIter {
		Box::new(self.nodes.into_iter())
	}
}

impl<'a> From<Vec<BoxDynElement<'a>>> for Elements<'a> {
	fn from(nodes: Vec<BoxDynElement<'a>>) -> Self {
		Elements { nodes }
	}
}