Trying to find an element in jQuery context

My goal is to find an element in context, in this case, a set of jQuery HTML elements.
It seems easy to me, but why does it fail?

s= "<h3 id='boi'> Oi putinho </h3> <p sub='a#b'> Oi oaosidoias aosd asoid aosidoi asodi sa </p>"

j(':first') // => [html]
j(s) // => [h3#boi, <TextNode textContent=" ">, p]
j(':first', j(s)) // => [] ?! Fail

ref: http://api.jquery.com/jQuery/#expressioncontext

+3
source share
2 answers

Use .filter.

$(s).filter(':first')

Or simply

s.filter(':first')
+3
source

If you want the first one, you can get it by its index using the jQuery method.eq() .

j(s).eq( 0 ); // Get wrapped element at index 0 (first item)

Or, if you just want the DOM element to be expanded, use the jQuery method.get() .

j(s).get( 0 ); // Get DOM element at index 0 (first item)

... or using square brackets.

j(s)[ 0 ]; // Get DOM element at index 0 (first item)

.slice().

j(s).slice( 0, 2 );  // Get the first two elements, wrapped in jQuery

, . @meder.

+3

Source: https://habr.com/ru/post/1774639/


All Articles