Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Create an element with the various attributes

Can you create an element without acting every time like that?

var button = document.createElement('button');
button.class = codebuttons;
button.value = Backup

For example

document.querySelector('.right.Sub').appendChild(document.createElement("button").setAttribute("class", "codebuttons"));
like image 968
Frostman Avatar asked Dec 05 '25 05:12

Frostman


1 Answers

Your "for example" code is very different from your code on top, but both need to be fixed.

First your initial code. That'll work except that you need to use .className to set the class. And of course you need quotation marks to create the strings.

var button = document.createElement('button');
button.className = "codebuttons";
button.value = "Backup";

Second, your bottom code won't work because you're not appending an element. You're appending the return result of .setAttribute(), which is undefined.

You can however chain .setAttribute() to the end of .appendChild() since it returns the appended element.

document.querySelector('.right.Sub')
        .appendChild(document.createElement("button"))
        .setAttribute("class", "codebuttons");

There are however issues in older versions of IE with setting the "class" using setAttribute(). So instead, set the property as in the first example.

document.querySelector('.right.Sub')
        .appendChild(document.createElement("button"))
        .className = "codebuttons";
like image 191
2 revsuser2437417 Avatar answered Dec 07 '25 19:12

2 revsuser2437417