JavaScript: How to set ID Attribute to all text inputs/textarea of a page

Well, sometimes we need to use ID Attributes of some HTML Elements of a web page. But, if any element lacks ID attribute, we’ll face trouble. So here is a script to automatically set IDs to all of your text <input type = “text”> tags and <textarea> Elements😉


First we’ll check if the element already has an ID attribute [i.e <input type = “text” id = “myId”>]

If it does has an ID, we will not change it. Else, we will set an ID dynamically to the content.

What we actually do?

  • Loop through all input elements
  • Check if it is a text field. If yes, we check if it already have an ID
  • If yes, continue. Else, dynamically set an iD

The Code

Here goes the code snippet, enjoy🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s