Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change content of span by id

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
}
like image 215
deerox Avatar asked Oct 22 '12 11:10

deerox


People also ask

Can we add ID to span tag?

Just as it is possible to style content by wrapping a span tag around it, you can also manipulate your content by wrapping it in a span tag. You give it an id attribute and then select it by its id with JavaScript so you can manipulate it.

How would you update the text written inside a span element with?

Use innerText is the best method. As you can see in the MDM Docs innerText is the best way to retrieve and change the text of a <span> HTML element via Javascript.

What is span id in JavaScript?

The <span> tag is an inline container used to mark up a part of a text, or a part of a document. The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id attribute. The <span> tag is much like the <div> element, but <div> is a block-level element and <span> is an inline element.

Can we use innerHtml in span?

Bookmark this question.


3 Answers

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'; 
like image 191
Denys Séguret Avatar answered Oct 16 '22 21:10

Denys Séguret


function set() {
    document.getElementByID('user').innerHTML = Owner; 
    // owner value is mike
}
like image 3
L.Grillo Avatar answered Oct 16 '22 20:10

L.Grillo


try:

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

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

like image 2
Ioana O Avatar answered Oct 16 '22 19:10

Ioana O