0
    <!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <p id="text">Javascript is -</p>
    <button id="firstpara">Click Me</button>
    <script type="text/javascript">
        document.getElementById("firstpara").onclick = function() {
            document.getElementById("text").innerHTML = "I THINK " + document.getElementById("text").innerHTML + " awesome";
        }
    </script>
</body>
</html>

https://jsfiddle.net/xpvt214o/411211/

The code adds "I think" before "javascript is" and "awesome" at the end when the button is clicked.

This doesn't work as expected it adds I think is awesome after The Text Javascript is

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <p id="text">Javascript is -</p>
    <button id="firstpara">Click Me</button>
    <p id="empty"></p>
    <button id="createText">Create Text</button>

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

    <script type="text/javascript">
            $("#firstpara").click(function() {
                $("#text").append("I think ") + $("#text").html() + $("#text").append(" is awesome");
            });
    </script>
</body>
1
  • It appears that you are asking two different questions. Your title suggests you want to know how to convert the script to jquery, but the question appears to be asking why your vanilla javascript is not working. Commented Jul 13, 2018 at 14:45

1 Answer 1

2

The literal translation of this would be to concatenate the string together. Note that you don't need append() for this, that has another meaning which is not relevant for this logic. Instead use html(), like this:

$("#firstpara").click(function() {
  $("#text").html("I think " + $("#text").html() + " is awesome");
});
<p id="text">Javascript is -</p>
<button id="firstpara">Click Me</button>
<p id="empty"></p>
<button id="createText">Create Text</button>

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

Alternatively you can provide a function to html() which receives the current value as an argument. This is more efficient as it means you don't need to select the #text element twice:

$("#firstpara").click(function() {
  $("#text").html(function(i, h) {
    return "I think " + h + " is awesome";
  });
});
<p id="text">Javascript is -</p>
<button id="firstpara">Click Me</button>
<p id="empty"></p>
<button id="createText">Create Text</button>

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

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

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.