kriszyp / put-selector

A high-performance, lightweight function for creating and manipulating DOM elements with succinct, elegant, familiar CSS selector-based syntax
Other
290 stars 39 forks source link

Adding element attributes that contain single quotes #29

Open raykendo opened 8 years ago

raykendo commented 8 years ago

So far, put-selector has been great. I haven't found anything it couldn't do... until now.

I have an application where I create text boxes for a search, and I inject data-attributes into those text boxes containing bits of tSQL statements. When the application collects the contents of those text boxes, it also collects the name attribute and the data-attribute that contains the tSQL statement template. I won't bore you with the rest.

When I use put() to create the text box inputs, I've had several errors when I use it to inject data-attribute strings containing single quotes. Here is a jsFiddle containing a test sample. When I try to assign element properties through an object following the "input", it silently fails to add the attribute (see cases 3 & 4). If I try to add element attributes within the put selector string (i.e. "input[type=text]"), it throws an error. I've tried escaping the single quotes within the text, and it throws an error (see case 6).

I did find a workaround, where I create the element without the possibly offending data-attribute, then assign the data-attribute afterward (see case 5). It's an extra line or two of code to safely implement a library that has saved me hundreds of lines already.

kriszyp commented 8 years ago

The problem with cases 3 & 4 is that object-based property assignment, does just that, property assignment, not attribute assignment. So adding the property: 'data-test':"field like '%value%'" results in an assigment like: element['data-test'] = "field like '%value%'" which doesn't really do anything productive. We could make a special case in the property assignment to detect data-* and convert it to a element.dataset[<data-name>] assignment.

Likewise, there probably should be better support for quote escaping. However, the simplest way to solve this problem would be with a parameterized selector. This seems to work properly:

put(listItem, "input[type=text][placeholder=test 1][data-test=$]", "field like '%value%'");

Anyway, sorry for the slow response, hopefully that helps.