Bramt
Bramt

Reputation: 45

Storing document.getElementById in a variable?

I have this script that is supposed to change the text of the button when the button is clicked.

<body>
   <button onclick="toggleText(this);" id="id">Edit</button>
</body>

function toggleText(element){
    var text = document.getElementById(element.id).textContent;

    if (text == 'Edit') {
        text = 'Done';
    } else {
        text = 'Edit';
    }
}

But it doesn't work. It only works when you put document.getElementById(element.id).textContent directly into the if statements.

How do I get the variable to store properly?

Upvotes: 0

Views: 18654

Answers (5)

srikanth t
srikanth t

Reputation: 21

Just use:

index.js

var mainText = document.getElementById("mainText").value;
document.write(mainText);

index.html

<textarea id="mainText"></textarea>

Upvotes: 2

Omar Elawady
Omar Elawady

Reputation: 3350

When you access document.getElementById(element.id).textContent you get the value of it, not the reference. So changes to it won't affect the element.

But when you assign element to variable, it gets reference to it.

var element = document.getElementById(element.id);
if (element.textContent == 'Edit') {
        element.textContent = 'Done';
    } else {
        element.textContent = 'Edit';
}

Upvotes: 6

Moishe Lipsker
Moishe Lipsker

Reputation: 3034

As tymeJV commented, you can store by reference the element you get by id. Its property is stored by value. Instead store the element in a variable and access its property from the variable.

var text = document.getElementById(element.id);

if (text.textContent == 'Edit') {
     text.textContent = 'Done';
} else {
    text.textContent = 'Edit';
}

Upvotes: 0

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31143

Since you already get the element, you don't need to get it again. You can just use element.

But the reason why you can't change it is that you're only changing the variable that contains the text. It does not point to the element's properties. You need to use this:

function toggleText(element){
  var text = element.textContent;

  if (text == 'Edit') {
    element.textContent = 'Done';
  } else {
    element.textContent = 'Edit';
  }
}

Upvotes: 9

Cyril CHAPON
Cyril CHAPON

Reputation: 3747

Is jquery an option ?

I used to do something like :

var a = $('#theid');
A.something

Upvotes: -3

Related Questions