Search code examples
javascripthtmljqueryattributestags

How to createElement tag with html attributes in Javascript


I inserted an input tag after a certain element of my html source code, it seems to work, but what I need is to be able to add attributes (type, class, id etc ..) to the input tag I created.

Here is what I did in Js

function insertAfter(referenceNode, newNode) {
  referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

var inputCheckBox = document.createElement("input");
inputCheckBox.innerHTML = "test";
var div = document.getElementById("plugin_delete_me_shortcode_password");
insertAfter(div, inputCheckBox);

Result html

<input type="password" autocomplete="off" autofocus="autofocus" id="plugin_delete_me_shortcode_password" name="plugin_delete_me_shortcode_password">

<input>test</input> <!-- i got this as a new item -->

Now I have two problems, 1) in general the input tags don't seem to have a closing tag, but they are one line. 2) I have no idea how I could add attributes to the tag via Js.

This is what I am trying to achieve Kindly, can someone show me the right way? I have searched some references but have not been able to find a solution. I appreciate any help, thanks.

<input type="password" autocomplete="off" autofocus="autofocus" id="plugin_delete_me_shortcode_password" name="plugin_delete_me_shortcode_password">

<input type="checkbox" class="my_class" id="my_id" onclick="my_function('example_function')"/>

Solution

  • You can just assign the a value to the attribute after creating the element like bellow:

    var inputCheckBox = document.createElement("input");
    
    inputCheckBox.type = 'checkbox';
    inputCheckBox.id = 'the-id';
    inputCheckBox.classList.add('the-class');
    
    // for styling
    inputCheckBox.style.color = 'green';
    
    // or you can use the set attribute method
    
    inputCheckBox.setAttribute('type', 'checkbox');
    console.log(inputCheckBox);