Computer's Guy
Computer's Guy

Reputation: 5363

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" ?

Upvotes: 4

Views: 12379

Answers (3)

Faiz Ahmed
Faiz Ahmed

Reputation: 1103

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 = "";
});

Upvotes: 5

Magicianred
Magicianred

Reputation: 566

The W3C standard way:

function functionAddAttribute(){
     document.getElementById('telheaderid').setAttribute('attributeName', 'attributeValue');
};
window.onload = functionAddAttribute;

for IE:

function functionAddAttribute(){
     document.getElementById('telheaderid').attributeName = 'attributeValue';
};
window.onload = functionAddAttribute;

Enjoy your code!

Upvotes: 1

Entimon
Entimon

Reputation: 184

Use this:

document.getElementById('telheaderid').setAttribute('class','YourAttribute')

Upvotes: 1

Related Questions