Change content of span by id
Asked Answered
O

5

11

I am trying to change john to mike. I have no idea why its not working.

<span id="user">John</span>

I am trying this but not working i have no clue why not working.

function set() {
    document['getElementById']('user')['value'] = Owner; 
    // owner value is mike
}
Oberland answered 22/10, 2012 at 11:45 Comment(2)
Why do you think span tag has a value?Perl
Why don't you use the obj.key syntax instead of obj['key']? For static keys that's the way to go. Nobody expects document['getElementById'] instead of document.getElementByIdAbjuration
T
19

If you want to change the id, use

 document['getElementById']('user').id = 'mike'; 

or, more classically,

 document.getElementById('user').id = 'mike'; 

If you want to replace "John" (that is not the ID but the content of the span), do

 document.getElementById('user').innerHTML = 'mike'; 
Teratism answered 22/10, 2012 at 11:46 Comment(2)
How changing id may change the node's text?Perl
@Perl Question title ("trying to change span id") and question content are different. That's why I provided a solution for each.Kestrel
A
3
function set() {
    document.getElementByID('user').innerHTML = Owner; 
    // owner value is mike
}
Astronomical answered 22/10, 2012 at 11:50 Comment(0)
P
2

try:

function set() {
    document.getElementById('user').innerText= Owner; 
    // owner value is mike
}

Where is Owner declared, is it valid in your function scope?

Pudens answered 22/10, 2012 at 11:48 Comment(3)
innerText is IE specific. It's now supported by Chrome but not Firefox.Kestrel
To be fair... that's not obvious. And the use of the textContent name by other browsers doesn't help.Kestrel
that's why I use jQuery, to abstract away browser specific stuff :)Pudens
S
2

You can try this

function set()
{
  var elem = document.getElementById('user'); 

  elem.innerHTML = "Owner";
}

if you want to add an **id** you can use **setAttribute()**
eg:

 document.getElementById('user').setAttribute('id','owner');

Note

 **value** attribute only work with input, text area,button etc..

eg:

 <input type="text" id="inid" value=""/>

 document.getElementById('inid').value = "Something";  // this will work
Sight answered 22/10, 2012 at 11:51 Comment(0)
B
1

For modern Browsers

document.getElementById("span_id_here").textContent="yourtext";
Boaten answered 5/4, 2015 at 7:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.