How to add attributes to an element that was created with JavaScript?

1

I created a elemento with JavaScript:

 $("<div />").addClass("placeholder").appendTo(element);

But I can not give attributes to it, how can I do this? I tried the following code, but it does not work:

$(document).ready(function(){
     $(".placeholder").addClass("fg-red");
 });

If I create it with HTML it works, however when I create with JavaScript the attempt to add attributes does not work

    
asked by anonymous 21.02.2016 / 02:01

3 answers

2

When you attach the new object <div /> , just add the classes you want:

Example 1

obj = $("<div />"); 
obj.addClass("placeholder");
obj.addClass("fg-red");
obj.appendTo(element);

Example 2

$("<div />").addClass("placeholder").addClass("fg-red").appendTo(element); 

Example 3

$("<div />").addClass("placeholder fg-red").appendTo(element); 
    
21.02.2016 / 12:59
1

I wrote something for you to analyze, to manipulate dynamically created elements use the Jquery ON function ( see )

<html>
    <head>

        <style>
            .verde {
                background:#0f0 !important;
            }

            #teste-area{
                background:#ccc;
                max-width:300px;
                min-height:100px;
            }

            .elemento {
                background:red;
                min-height:50px;
                margin: 5px;
            }
        </style>
        <script src="https://code.jquery.com/jquery-1.11.3.js"></script></head><body><p><ahref="#" id="criar">Criar Elemento</a>
        </p>
        <p>
            <a href="#" id="add">Adicionar Atributo ao Elemento Dinamicamente</a>
        </p>

        <div id="teste-area"></div>

        <script>
            $(document).ready(function(){    
                $('#criar').click(function(e){
                    console.log("nojento");
                    $("<div><center>Elemento Adiciona</center></div>").addClass("elemento").appendTo($('#teste-area'));
                });

                $('body').on('click','#add', function(e){
                    $(".elemento").addClass("verde").empty().html("<center>Elemento Alterado Dinamicamente</center>");     
                    });
            });
        </script>

    </body>
</html>
    
21.02.2016 / 12:34
0

Because your object is being created dynamically, use:

$(document). on (function (){
      ... aqui o que você quer fazer, no caso o addClass

}
    
21.02.2016 / 02:26