Sean Poh Sean Poh - 1 month ago 8
Javascript Question

When I click Element A, I want to change text of Element B

The idea is that when I click on h1.question, the string in h1.answer will change to the string in h1.question's data-text-swap. For example, if I click "What is wrong with you?", I should see the answer "Nothing" at h1.answer.

I've tried using .text() but I think it isn't the right answer because I plan to put 10 questions and writing .text() 10 times is a bit ridiculous.

Help!

Update: Wow! Thanks so much for the answers! All the answers here have been really swift and easy to understand. I'm going to look at them again tonight. Thanks so much!!

<h1 class="answer">Answer here</h1></div>
<h1 class="question" data-text-swap="Nothing">What is wrong with you?</h1>
<h1 class="question" data-text-swap="Good!">How is the weather today?</h1>
<h1 class="question" data-text-swap="Everything">What is wrong with him?</h1>


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script>
$("h1.question").click(ontop);
function ontop() {
$("h1.answer").text(("h1.question").data("text-swap"));
}
</script>

Answer

Two problems:

  1. You are missing the $ from $("h1.question").data(...)
  2. In that same line, to get the text of the clicked item use $(this) instead of $("h1.question")

That is, change:

$("h1.answer").text(("h1.question").data("text-swap"));

To:

$("h1.answer").text($(this).data("text-swap"));

In context:

$("h1.question").click(ontop);
function ontop() {
    $("h1.answer").text($(this).data("text-swap"));
}
<h1 class="answer">Answer here</h1></div>
<h1 class="question" data-text-swap="Nothing">What is wrong with you?</h1>
<h1 class="question" data-text-swap="Good!">How is the weather today?</h1>
<h1 class="question" data-text-swap="Everything">What is wrong with him?</h1>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Comments