0

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 ...";
3
  • 2
    Show your JavaScript, you did something wrong, but we can't see what. Commented Jul 19, 2012 at 14:49
  • Peter Pajchl has the answer - that was it Commented Jul 19, 2012 at 15:26
  • Still would have been nice to see the code that caused the error. Commented Jul 19, 2012 at 15:31

3 Answers 3

2

Since it says with javascript not jquery...

yourElement.setAttribute('data-placeholder','value');
Sign up to request clarification or add additional context in comments.

1 Comment

Short, concise and beautiful. Can you please send me a link of this documentation?
1

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!

Comments

-1

JQuery makes this easy:

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

8 Comments

+1, you could also write $("<select></select>").data("placeholder", "value") // ...
@epascarello - There doesn't need to be one, it's still a solution.
It is like suggesting a person use a hammer to open a window. It is a tool that does the job.
AND you should be using data() and not attr(). ;p
@epascarello - so by your logic, I can't suggest they type on a keyboard because they haven't tagged it? Genius right there..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.