Bardelman Bardelman - 3 months ago 9
HTML Question

How to use $('<li>') as a jquery selector?

I found a strange jquery selector using html tag declaration and not just the tag name :

$('<li />')
and i couldn't find such as selector in the jquery documentation nor in the W3C reference for it.

this is the piece of code where i found it (it's used to create a new list item to be appended to an unrodred list)

$title.on("keyup", e => {
const title = e.target.value;

console.log('typed value : ' + title);

getItems(title)
.then(items => {
$results.empty();

const $items = items.map(item => $('<li />').text(item));
$results.append($items);
})
})


Please , i need to know more about such as selector (or if it's not a selector but a way to create new components) and its role.

Answer

It's not a selector. It's used for creating new elements in a well-looking way!

Description: Creates DOM elements on the fly from the provided string of raw HTML.

For example, you can write:

$('<div></div>')
    .addClass('myclass')
    .attr('id', 'myid')
    .append($('<span></span>')
                .text('Hi there')
                .css('color', 'red'))
    .appendTo('body');

this code snippet creates the following element

<div id='myid' class='myclass'>
    <span style='color: red'>
        Hi there
    </span>
</div>

and appends it to the body.