Reputation: 434
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
Upvotes: 4
Views: 20466
Reputation: 1721
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.
Upvotes: 11
Reputation: 983
Yes, you can set the title attribute for an HTML element dynamically.
For example, if one of your form inputs had the id of "foo", you can set it using the following example. Since you want to do it after the document is ready, you can use the jQuery $(document).ready().
$(document).ready(function() {
var newTitle= document.getElementById("foo").type;
document.getElementById("foo").title = newTitle;
// Alternatively,
var newTitle = document.getElementById("foo").type;
document.getElementById("foo").setAttribute("title", newTitle);
});
Upvotes: 1
Reputation: 2211
You can use following solutions:
document.getElementsByTagName("H1")[0].setAttribute("class", "democlass"); //Using Tag
document.querySelector(".class").setAttribute("class", "democlass"); //Using Query Selector
document.getElementById('YOURID').setAttribute('title', 'NEW TITLE');
Using Jquery
$("#id").attr("kin","kin");
The setAttribute() method adds the specified attribute to an element and gives it the specified value.
If the specified attribute already exists, only the value is set/changed.
Note: Although it is possible to add the style attribute with a value to an element with this method, it is recommended that you use properties of the Style object instead for inline styling because this will not overwrite other CSS properties that may be specified in the style attribute:
Upvotes: 1