Create elements and set attributes inside each other using jquery?

Answer found: D

I'm new to jQuery, and I know that there are some really nice quick tricks that do such things, so I know how to answer this question in JavaScript in 30 lines of code.

Current Code:

$('<li>, <a>', {
    id: '#tab-' + count
}).html($(this).text()).appendTo('#uls');

I want to add a tagwith dynamic href. Do I need to do this in a separate piece of code, or can I somehow integrate it with the current code.

What I'm trying to create:

<li><a href="#tabs-1"> text describing url </a></li>

+3
source share
3 answers

You can either create a mix from creating a jQuery element + HTML string, or create a clean element:

Mix:

$('<li>', {
    html: '<a href="' + some_variable + '">' + $(this).text() + '</a>',
    id: '#tab-' + count
}).appendTo('#uls');

Methodical:

$('<li>', {
    id: '#tab-' + count
}).append($('<a>', {
    href: some_variable,
    text: $(this).text()
})).appendTo('#uls');
+7
source

Something is wrong with

$('#uls').append(
    $('<li>').append(
        $('<a>', { href: url, text: 'text', id: 'theid'})
    )
);

(I have not tested it, though ...)

+2
source

one dirty line

$("<li><a href='" + href + "' id='#tab-" + count + "'>" + $(this).text() + "</a></li>").appendTo("#ul");
+1
source

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


All Articles