JessieBear JessieBear - 7 months ago 23
Javascript Question

Add list item with attributes in Jquery

I am trying to add a list item with attributes but every time I run it I get an error. Do you know guys what is the syntax issue with my code?

<div class="subway-map" data-columns="12" data-rows="10" data-cellSize="40" data-legendId="legend" data-textClass="text" data-gridNumbers="true" data-grid="true" data-lineWidth="8">
<ul data-color="#ff4db2" data-label="jQuery Widgets">
<li data-coords="2,2"><a href="#">North Ave</a></li>
<li data-coords="4,2"><a href="#">South</a></li>
<li data-coords="6,2"><a href="#">West</a></li>
</ul>

<ul data-color="red" data-label="jQuery Interactions" class="map2></ul>
</div>


$(".subway-map").subwayMap({ debug: true });
$(".map2").append("<li data-coords="2,4">Test</li>"); // This is the issue

Answer

The problem is because you delimit the string literal with double quotes and use double quotes within the string. You can fix this by using single quotes around the string itself. Try this:

$(".map2").append('<li data-coords="2,4">Test</li>');

Alternatively you can use double quotes for both, but you need to escape them with a \ within the string:

$(".map2").append("<li data-coords=\"2,4\">Test</li>");

I would suggest you look in to using an editor with syntax highlighting as it makes it almost impossible to miss errors like this.