skip to Main Content

I’m unable to edit a h1 tag without changing the css. Here is the string without the javascript:
without JS

Here is the string with the javascript:
with js

I’m not having this problem elsewhere. THe rest of the code snippets were properly manipulated by the JS code.
Here is the HTML and JS snippets:

document.getElementById('currentContact').innerText = state.translate('test');
  <div class="class_Name" id="currentContact">
                    <h1>test</h1>
                </div>

Troubleshooting:

  • Tried moving the div to between the tags
  • Tried innerHTML, textContents, innerText.

I expect the manipulated string to keep the same styling.

3

Answers


  1. It is because you are replacing the <h1> element when you set the innerText property. Target and manipulate the <h1> element inside the <div> instead, like:

    const state = { translate: () => 'foo' };
    
    document.querySelector('#currentContact h1').innerText = state.translate('test');
    <div class="class_Name" id="currentContact">
      <h1>test</h1>
    </div>
    Login or Signup to reply.
  2. try stuffing
    document.getElementById(‘currentContact’).innerText = state.translate(‘test’);
    to a variable, like let text, then call text.style.color = ‘red’;
    maybe I misunderstood your question

    Login or Signup to reply.
  3. Your currentContact is the <div> that contains the <h1>. If you change the innerText of currentContact, it will completely override the <h1>.

    As a solution, you could give your <h1> element the id currentContact. or insert a new <h1> when you assign a new value to innerHTML instead of innerText.

    document.getElementById('currentContact').innerText = "el testo";
    <div class="class_Name" >
        <h1 id="currentContact">test</h1>
    </div>
    document.getElementById('currentContact').innerHTML = "<h1>el testo</h1>";
    <div class="class_Name" id="currentContact">
        <h1>test</h1>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search