0

I'm trying to create an element with an element inside of it in JQuery, but I'm not getting anything when I try and output it.

This is the HTML equivalent of what I'm looking for:

HTML:

<div class="btn-icn">
   <button class="btn">
      <span class="glyphicon glyphicon-comment"></span>
   </button>
</div>

Jquery:

a = $(button).attr({
     class: "btn";
     id:"btn";
 }.append($(icon).attr({
     class:"glyphicon glyphicon-comment";
     id="comment";
 }));

alert(a);
3
  • what are inside button and icon variables? Commented Mar 30, 2016 at 16:59
  • 1
    That indentation though... Pretty sure there is a syntax error somewhere. Commented Mar 30, 2016 at 17:00
  • @Karl-AndréGagnon not one but 5 syntax errors Commented Mar 30, 2016 at 17:03

2 Answers 2

1

$("<button/>", { // here goes the properties:
  appendTo : ".btn-icn",
  class : "btn",
  id : "btn",
  on : {
      click : function(){ alert(this.tagName); }
  },
  append : $("<span/>", {
    class : "glyphicon glyphicon-comment",
    id : "comment"
  })
});
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 
<div class="btn-icn"></div>

(Be aware that using an ID multiple times on a single page is wrong. Stick with classes instead.)

Sign up to request clarification or add additional context in comments.

Comments

0

The jquery code is totally broken to me:

var a = $('<a />').attr({
  class: "btn", //comma not semicol
  id:"btn"
});

var icon = $('<i></i>').attr({
  class: "glyphicon glyphicon-comment",
  id: "comment" //no equal sign in an object, property: value
});

a.append(icon)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.