1

I have some jQuery where I am appending text where some of their attributes take some js variables.

<script>
var className = "COS 102";
var teacher = "Bob Teacher";

$("#classesDiv").append("<div className="+className+" teacher="+teacher+" class='class'></div>");
</script>

The issue I am having is that when I pass these variables into the element it comes out looking like className="COS", without the 102 after.

Does anybody know why this is happening?

John
  • 1
  • 13
  • 98
  • 177
Nicolas
  • 1,125
  • 1
  • 15
  • 31
  • `COS 102` is not a valid class name, that's a class name of `COS` and an invalid classname `102`, [refer here](http://stackoverflow.com/questions/448981/what-characters-are-valid-in-css-class-selectors) for a better explination – Brett Santore Jul 11 '14 at 19:42
  • 5
    @BrettSantore it's not *className* as an HTML class, but a custom attribute *className* as in a school class. – Karl-André Gagnon Jul 11 '14 at 19:43
  • Ah, sorry about that, should have read more thoroughly, saw `className` and reacted. – Brett Santore Jul 11 '14 at 19:44

3 Answers3

13

Because you don't have quotes around the attribute values.

Your code is going to append:

<div className=COS 102 ...

when it should append

<div className='COS 102' ...

This should work:

<script>
var className = "COS 102";
var teacher = "Bob Teacher";

$("#classesDiv").append("<div className='"+className+"' teacher='"+teacher+"' class='class'></div>");
</script>
Mike
  • 4,071
  • 21
  • 36
4

Think about the string you're appending:

<div className=COS 102 teacher=Bob Teacher class='class'></div>

Since those attribute values aren't quoted, 102 and Teacher are seen as separate, value-less attributes. You'll want to get:

<div className='COS 102' teacher='Bob Teacher' class='class'></div>

by quoting:

$("#classesDiv").append("<div className='" + className + "' teacher='" + teacher + "' class='class'></div>");

Or, to be more jQuery-ish about it:

$('<div>').
  attr({
    'className' : className,
    'teacher' : teacher
  }).
  appendTo($('#classesDiv'));

An advantage to the last approach: it works even if teacher or className contain quotes (either single or double), or other characters that are meaningful to HTML.

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
2

It's happening because you're constructing an element by joining strings together. As you can see, this approach is fragile. Construct the element by passing an object to jQuery's $ function:

var className = 'COS 102';
var teacher = 'Bob Teacher';

$('<div>', {
    className: className,
    teacher: teacher,
    'class': 'class'
}).appendTo('#classesDiv');

Also, custom attributes like className and teacher are not valid HTML. You must prefix them with data-:

$('<div>', {
    'data-className': className,
    'data-teacher': teacher,
    'class': 'class'
})
Blender
  • 289,723
  • 53
  • 439
  • 496