0

in this example, i have a button which has to change the text. Now I know that I can use the onclick=document.getElementById('id').innerHTML="text" but I am making a function such that

**onclick = myFunc()**


 <script>
    function myFunc()
    var x = document.getElementById('id');
    x.style.property = 'text';
    </script>

so my question is , is there any property I can use which will change the text

3
  • 1
    If you know you can use innerHTML why won't you use it? Commented Nov 26, 2016 at 13:01
  • w3schools.com/jsref/… Commented Nov 26, 2016 at 13:06
  • You could use the textContent property rather than innerHTML, but there's no CSS property available to JavaScript that can change the text of an element. Although you could use the content CSS property on generated elements which, so far as I know, are read-only to JavaScript. And even then will only read the original string, not the computed value (in the event of using attr() or counter() to set the value. Commented Nov 26, 2016 at 13:07

3 Answers 3

1

No. "Style" properties are for styling. With a few very specific exceptions, they are only for changing the look of the content. Not changing the content itself.

There are other alternatives to innerHTML. innerHTML is for adding HTML content to the element.

One alternative is textContent. Which adds plain text to the element.

var x = document.getElementById('foo');
x.textContent = 'text';
<button id="foo">Hello World</button>

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

Comments

0

You can set text using :

<script>
    function myFunc(){
      var x = document.getElementById('btntext');
      x.style.color = "green";
      x.style.fontSize = "large";
      x.value = "This is new TExt";
   }
</script>
<body>
<input type="text" id="btntext" value="This test"/>
<button onClick="myFunc()" name="send">change color</button>
</body>

Comments

0

function changeText(id) {
    id.innerHTML = "Text has been changed!";
}
<h1 onclick="changeText(this)">Click on this text!</h1>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.