Home > Net >  How to createElement tag with html attributes in Javascript
How to createElement tag with html attributes in Javascript

Time:08-05

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"  id="my_id" onclick="my_function('example_function')"/>

CodePudding user response:

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);

CodePudding user response:

Try to call setAttribute on inputCheckBox like`

inputCheckBox.type = 'password';    
inputCheckBox.setAttribute('autocomplete', 'off');
...
inputCheckBox.name = "plugin_delete_me_shortcode_password";

CodePudding user response:

You can use DOM for Vanilla JavaScript

const element = createElement("div");
div.setAttribute("data-custom-attribute", "custom-value");

If you want to use JQuery:

$('<div></div>').attr({
  id: "my-id"
})

More on this on the official documentation

  • Related