Kalpesh Jain
Kalpesh Jain

Reputation: 409

javascript setAttribute

I am using javascript setAttribute for following to change 'lorem ipsum' to 'coming' in the following manner :

<span id="pop_title" name="pop_title" class="title01_mc10401 ff_1 fs_10 fc22 fsb">lorem ipsum</span>

Script:

function modifyDOM(){
  var elem_pop = document.getElementById("pop_title");
  elem_pop.setAttribute("value","coming");
}

When I inspect in firebug, its showing that the value attribute is added with coming, but its reflecting in the browser (I am using mozilla 3.0.5) What may be the issue ?? do i need to set different attribute ??

Upvotes: 1

Views: 5711

Answers (3)

Oded
Oded

Reputation: 498904

The span element does not have a value attribute. Try setting its innerHTML instead:

elem_pop.innerHTML = "coming";

Upvotes: 2

lucideer
lucideer

Reputation: 3882

There are two ways to do this (correctly). You can use this cross-browser method here:

elem_pop.appendChild( document.createTextNode('coming') );

The other way is to use elem_pop.textContent and/or elem_pop.innerText, but these unfortunately don't work cross-browser. IE only supports innerText, Firefox, Chrome only support textContent - Opera is the only one that supports both.

You could use elem_pop.innerHTML, HOWEVER be aware that innerHTML inserts HTML markup, NOT just text into the page. This means that it won't escape any special characters into entities. It also replaces any child nodes automatically and can destroy event listeners.

I'd recommend the first (appendChild()) method, but if you want to use textContent/innerText you could place this at the top of your script:

HTMLElement.prototype.__defineGetter__('innerText', function(){ return this.textContent; });
HTMLElement.prototype.__defineSetter__('innerText', function(t){ this.textContent=t; });

That will give Firefox innerText support and you can use it all you like.

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630349

Use .innerHTML instead here, like this:

function modifyDOM(){
  var elem_pop = document.getElementById("pop_title");
  elem_pop.innerHTML = "coming";
}

You can try it here. Setting the value attribute would be for something like an <input> element, when you want to replace the html within an element's tags, use .innerHTML instead.

Upvotes: 1

Related Questions