1 use webcore::value::Reference; 2 use webcore::try_from::TryInto; 3 use webapi::element::Element; 4 5 /// The `HtmlCollection` interface represents a generic collection 6 /// (array-like object similar to arguments) of elements (in document order) 7 /// and offers methods and properties for selecting from the list. 8 /// 9 /// An `HtmlCollection` in the HTML DOM is live; it is automatically 10 /// updated when the underlying document is changed. 11 /// 12 /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection) 13 // https://dom.spec.whatwg.org/#interface-htmlcollection 14 #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] 15 #[reference(instance_of = "HTMLCollection")] 16 pub struct HtmlCollection( Reference ); 17 18 impl HtmlCollection { 19 /// Returns the number of elements in the collection. 20 /// 21 /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection) 22 // https://dom.spec.whatwg.org/#ref-for-dom-htmlcollection-length 23 pub fn len( &self ) -> u32 { 24 js!( return @{self}.length; ).try_into().unwrap() 25 } 26 27 /// Returns an element from an `HtmlCollection` by index. 28 /// 29 /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection/item) 30 // https://dom.spec.whatwg.org/#ref-for-dom-htmlcollection-item 31 pub fn item( &self, index: u32 ) -> Option< Element > { 32 js!( 33 return @{self}.item(@{index}); 34 ).try_into().unwrap() 35 } 36 37 /// Returns an iterator over the collection. 38 pub fn iter( &self ) -> ElementIter { 39 ElementIter { 40 list: self.clone(), 41 index: 0 42 } 43 } 44 } 45 46 47 impl IntoIterator for HtmlCollection { 48 type Item = Element; 49 type IntoIter = ElementIter; 50 51 #[inline] 52 fn into_iter( self ) -> Self::IntoIter { 53 ElementIter { 54 list: self, 55 index: 0 56 } 57 } 58 } 59 60 impl< 'a > IntoIterator for &'a HtmlCollection { 61 type Item = Element; 62 type IntoIter = ElementIter; 63 64 #[inline] 65 fn into_iter( self ) -> Self::IntoIter { 66 ElementIter { 67 list: self.clone(), 68 index: 0 69 } 70 } 71 } 72 73 #[derive(Debug)] 74 pub struct ElementIter { 75 list: HtmlCollection, 76 index: u32 77 } 78 79 impl Iterator for ElementIter { 80 type Item = Element; 81 fn next( &mut self ) -> Option< Self::Item > { 82 let item = self.list.item(self.index); 83 self.index += 1; 84 item 85 } 86 } 87