3

I have a paragraph inside a div:

HTML:

<div id="header"><p>Header</p></div>

CSS:

#header p {
color: darkgray;
font-size: 15px;

When a button is clicked, the innerHTML Changes:

Javascript:

var header = document.getElementById('header')
header.innerHTML = "Changed"

However, the after innerHTML is changed, the text returns to its original attributes. I would like the text to keep its color (darkgray) and font size (15px).

Here is a JS Fiddle

1 Answer 1

3

It's not working because you're subsequently removing the nested p element (which is what the CSS is being applied to).

You could select the first child node and then change the textContent property:

Updated Example

var header = document.getElementById('header');
header.childNodes[0].textContent = "Changed";

The benefit to accessing the childNodes property is that it will either select a child element or a text node. This means that the text will be changed even if the #header element doesn't contain a descendant p element.

In other words, it would replace the text in <div id="header"><p>Header</p></div> and <div id="header">Header</div>.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.