Error: SyntaxError: DOM 12 exception when creating tags Using jQuery

I have the following javascript:

var orderItemQuantity = $('<input/>', { type: 'hidden', name: 'order_detail[][quantity]', value: itemQuantity }); 

In the above javascript, the following error message appears:

 Error: SyntaxError: DOM Exception 12 

This works without errors:

 var newListItem = $('<li/>', { html: $('#item_name_'+itemId).text() + '(' + $('#item_quantity_' + itemId).val() +')' + '<a onclick="removeItem(' + itemId + ')">Delete this</a>' + '<input type="hidden" name="order_detail[][item_id]" value="' + itemId + '"/>', id: itemId }); 

I checked the following question , but the answer did not clearly indicate the correct reason WHY.

Here is my DTD:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

Question : why $('<input/>') and $('<input>') throw the specified exception, and $('<li/>') not a problem?

+8
javascript jquery dom syntax-error dtd
source share
1 answer

Make sure jQuery is loaded in the first example.

Even if you don't have jQuery loaded, the $() function is now defined by Google Chrome as something similar to querySelectorAll() .

This function accepts only the CSS selector as a parameter, and not arbitrary HTML, such as jQuery $() .

From the docs:

Code SYNTAX_ERR 12 In the indication of an invalid or invalid string; for example, setting the selectorText property to CSSStyleRule with an invalid CSS value.

The function expects a CSS selector, and you gave it HTML to give a syntax error.

Look at this fiddle, it works great:

http://jsfiddle.net/S6d6w/

+9
source share

All Articles