Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an attribute to html element with javascript on page load?

What I've tried:

function addAttribute(){
     document.getElementById('myid')... 
};
window.onload = addAttribute;

How can I add add the attribute to my element with id="myid" ?

like image 789
Computer's Guy Avatar asked Sep 05 '25 16:09

Computer's Guy


2 Answers

document.getElementById('telheaderid').yourattribute = "your_value";

For instance

document.getElementById('telheaderid').value = "your_value";

Using jQuery:

$('#telheaderid').attr('value', 'your_value');

EDIT:
Focus is the event that fires up when an element get focused or for instance when we click on the textarea it highlights thats the time.

Using jQuery:

$('#telheaderid').focus(function() {
   $(this).val('');
   // run any code when the textarea get focused
});

Using plain javascript:

document.getElementById('telheaderid').addEventListener('focus', function() {
   this.value = "";
});
like image 124
Faiz Ahmed Avatar answered Sep 07 '25 08:09

Faiz Ahmed


Use this:

document.getElementById('telheaderid').setAttribute('class','YourAttribute')
like image 40
Entimon Avatar answered Sep 07 '25 08:09

Entimon