There is an element in <body> <p><input id="btn" name="btn" type="submit" value="Click"></p> and <ol id="list"></ol> . When you click a button, a list should be created, processed by the function:

 $('#btn').click(function(e){ $('<div id="divM1"/>').appendTo($( "#list" )); $('<span />').addClass('expandEditor ui-icon ui-icon-triangle-1-n').appendTo($( "#divM1" )); $('<span id="span1"/>').appendTo($( "#divM1" )); $('<span id="span2"/>').addClass('itemTitle').appendTo($( "#span1" )); $('<input type="text" value="Name menu"/>').addClass('textDiv').appendTo($( "#span2" )); $('<div id="divM2"/>').addClass('menuEdit hidden').appendTo($( "#divM1" )); $('<p id="par"/>').appendTo($( "#divM2" )); $('<input type="text" value="MyText"/>').addClass('text').appendTo($( "#par" )); }); 

In the third line, the expandEditor class should be applied to the span. But it does not work.

Js:

 $('.expandEditor').attr('title','Click to show/hide item editor'); $('.expandEditor, .itemTitle').click(function(){ var id = $(this).attr('data-id'); $('#menuEdit'+id).toggle(); $(this).toggleClass('ui-icon-triangle-1-n').toggleClass('ui-icon-triangle-1-s'); }); 

How can I apply class properties to a tag? Maybe there is a more convenient way to add elements to the page?

    1 answer 1

    Therefore, in general, it is recommended to write

     $(document).on('click', '.class', function(){ ... }); 

    Instead

     $('.class').on('click', function(){ ... }); 

    The first will work in any case, when would not have added an element to the page.
    And the second binds the event only to those .class elements that have already appeared on the page after loading.

    Ps attr('data-id') == data('id');

    • You mean replace $ ('. ExpandEditor, .itemTitle'). Click (function () {...}); on $ (document) .on ('click', '.expandEditor, .itemTitle', function () {...}); If so, then var id = $ (this) .attr ('data-id'); There is no id in this line. I pass this parameter in the button handler: $ ('<div id = "menuEdit555" />'). addClass ('menuEdit hidden'). appendTo ($ ("# divM1")); - Alin
    • @Alin var id = this.id; - Igor
    • in this case, id is not defined. the console displays undefined - Alin
    • Because they mixed up id and data-id) If in HTML we have <div id="bubu" data-id="moo"></div> In this case, this.id will be equal to bubu; and this.dataset.id = moo; Analogue to jQ: $(this).attr('id') is bubu, and $(this).data('id') will be moo (everything written assumes that some function was bound to a div so that when a function was started, this div itself selected it) - OPTIMUS PRIME
    • Indeed, I had everything messed up with id. Revising these parameters, everything turned out. Thanks you. - Alin