Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set title attribute for HTML element dynamically?

I have a different set of HTML element like "Text, radio, checkbox & number etc." & I want to set title attribute for all my HTML field dynamically is it possible to set when page load.

and also all title value copied from respective HTML filed ID.

Thanks

like image 428
Pramod Avatar asked Aug 31 '25 17:08

Pramod


1 Answers

Yes, it is possible. On page load simply set it like:

 document.getElementById('YOURID').setAttribute('title', 'NEW TITLE');

EDIT : Based on the comment, I got that you want to set the title of all elements same as their ID. Let's say you want to do it only within your body tag, then your code will look like:

var children = document.getElementsByTagName("body").getElementsByTagName('*');
//Now children variable has all DOM elements inside `body`
 for (i = 0; i < children.length; ++i) {
 var ele = children[i];
 ele.setAttribute('title',ele.getAttribute("id"));
}

You may want to place some checks before assigning any value or prevent in errors in console.

like image 199
PM. Avatar answered Sep 02 '25 07:09

PM.