0

This script is supposed to add a button and the button needs to link to xyz.com. I am able to get the button to display, but it does not link. Here's what I have:

<script type="text/javascript">
var btn = document.createElement('button');
btn.innerText = 'Watch Now';
document.getElementById('buttoncontainer').appendChild(btn);
document.getElementById("buttoncontainer").href = "http://www.cnn.com/";
</script>

Thanks, Udi

2
  • 3
    A button does not have an href attribute (that actually does anything) Commented Apr 16, 2018 at 19:36
  • Buttons aren't the same as links. Commented Apr 16, 2018 at 19:36

1 Answer 1

2

If you want a button to navigate, you'll have to add a bit more than what you have because button elements don't have an href attribute and don't produce navigation by default. You'll need to set up a click event handling callback function for that.

Also, don't use .innerText as it is non-standard. Use .textContent instead.

<div id="buttonContainer">
</div>
<script>
  var container = document.getElementById('buttonContainer');
  var btn = document.createElement('button');
  btn.textContent = 'Watch Now';
  
  // Buttons don't have an href. You need to set up a click event handler
  btn.addEventListener("click", function(){
    location = "https://cnn.com"; // Navigate to new page
  });
  
  // Add button to page
  container.appendChild(btn);
</script>

If you want a hyperlink (<a>), then you can work with href:

<div id="buttonContainer">
</div>
<script>
  var container = document.getElementById('buttonContainer');
  var a = document.createElement('a');
  a.textContent = 'Watch Now';
  a.href = "https://cnn.com";
  
  // Add hyperlink to page
  container.appendChild(a);
</script>

NOTE:

Neither of these will actually navigate you to CNN here in the Stack Overflow code snippet environment, due to security restrictions, but the code will work in your own environment.

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

3 Comments

I've seen textContent and innerText and innerHTML and wasn't totally clear which was the new shiny best one to use (if any). Thanks for the link. I didn't know that textContent auto-encoded HTML. That's really snazzy!
@Anthony .textContent is for getting/setting text that does not include HTML that you want parsed. .innerHTML is for getting/setting text that does contain HTML that you want parsed and innerText is legacy code that is non-standard and should not be used. Good luck and don't forget to mark my answer as "the" answer.
sorry, buddy. Not the OP. Just was glad to have had an excuse thanks to your answer to finally mess around with innerText and see how it works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.