Reputation: 277
I want to create a select element through JavaScript and I want to set an attribute to it called data-placeholder
.
How can we assign non-standard attributes with JavaScript without the browser complaining with:
Uncaught referenceError: Invalid left-hand side in assignment
Code that cause the error:
select1.data-placeholder="Choose ...";
Upvotes: 0
Views: 769
Reputation: 3240
Here's a pretty simple non-jQuery way to achieve this;
var el = document.createElement('select');
el.setAttribute('data-placeholder', 'placeholder value');
document.body.appendChild(el);
I've created a very simple JSFiddle to demonstrate it.
Hope that helps!
Upvotes: 1
Reputation: 2709
Since it says with javascript not jquery...
yourElement.setAttribute('data-placeholder','value');
Upvotes: 2
Reputation: 61599
JQuery makes this easy:
$("<select></select>").attr("data-placeholder", "value").appendTo($element);
Upvotes: -1