HTML and Javascript integration

Asked

Viewed 405 times

4

I am doing some initial tests with javascript, and I am not succeeding in trying to change a parameter of my HTML code. The idea is that when you click the "Message" button, the text is updated to "New Text!" Follow the HTML code and javascript:

<html>
<h1>Javascript</h1>
<h3 id="frase">Default text</h3>
<button id = "getMessage" class = "btn btn-primary"> Message </button>
</html>

$(document).ready(function() {
  $("#getMessage").on("click", function(){
    document.getElementById("frase").innerHTML = "New text!";
  });
});

How should I integrate what is displayed in HTML with my javascript code?

  • 1

    Matheus, Welcome! Your question is unclear... the code you have is right and works (see here: https://jsfiddle.net/c56mg0m6/). What problem are you having to implement that?

2 answers

4


Need to add jQuery bookstore and also need to insert TAG SCRIPT for the Javascript code.

Run the code below and see the script working.

<html>
<h1>Javascript</h1>
<h3 id="frase">Default text</h3>
<button id="getMessage" class="btn btn-primary"> Message </button>
</html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
$(document).ready(function() {
  $("#getMessage").on("click", function(){
    document.getElementById("frase").innerHTML = "New text!";
  });
});
</script>

2

As mentioned, you are using code that is based on jQuery. You’d have to include it first through a tag <script/>.

Being already included, you could rewrite your code as follows:

<script>
$(function() {
  $('#getMessage').on('click', function(){
    $('#frase').text('New Text!');
  });
});
</script>

The difference here is as follows:

  • $(function(){}) is a shortcut by document.ready
  • Since you’re getting hair id of #getMessage, can do the same in #frase
  • $('#frase').text() swap the text inside. If you’re going to put HTML (e. g. <span>Algo</span>), would use $('#frase').html()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.