skip to Main Content

Lets say I have variable x.

x is equal to document.querySelector('h1').textContent;

Is it possible to set the value of text content rather than reassigning the value of the variable using = or some other JavaScript operation? I know that I could just set x to document.querySelector('h1'); and reassign the text by doing x.textContent = 'Hello.' I’d just like to know if there is some operation to avoid that.

I’ve tried changing the variable type to let, const, and var.

When I do this

let x = document.querySelector('h1').textContent;
x = 'Hi.'

It only reassigns the x variable to hold the value ‘Hi.’
I wanna know if there’s a way to assign the textContent of h1 using the variable without having to change the value of the variable to hold just the h1 element.

I can’t come up with a google search query that gives back the results I want. "How to change the value of the data held in the variable rather than the variable" is the best I’ve come up with and nothing matches what I’m searching. Thanks.

2

Answers


  1. Strings are immutable in JavaScript. They can’t be altered. You need to reassign the property or call a setter on the object holding the string when you want to change the string being held.

    With mutable objects, this is easy:

    const x = [];
    x.push(1);
    

    But this only works because arrays have methods on them that allow them to be mutated (via push here). Strings don’t expose any such methods because they don’t support mutation.

    Login or Signup to reply.
  2. i think you can do like this

    let x = document.querySelector('h1');
    
    function updateTextContent(newText)
    {
      x.textContent = newText
    }
    
    //now you can call like this:
    updateTextContent('Hi.');
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search