aurora
aurora

Reputation: 277

Add non-standard attribute to a select tag with Javascript

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

Answers (3)

jasonmerino
jasonmerino

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

Peter Pajchl
Peter Pajchl

Reputation: 2709

Since it says with javascript not jquery...

yourElement.setAttribute('data-placeholder','value');

Upvotes: 2

Matthew Abbott
Matthew Abbott

Reputation: 61599

JQuery makes this easy:

$("<select></select>").attr("data-placeholder", "value").appendTo($element);

Upvotes: -1

Related Questions