madlad
madlad

Reputation: 13

Get innerHTML of content when it is clicked

I'm trying to get the text of the p tag to change to the text from the li that tag I click. However, It always changes to the first one.

Javascript

$('li').click(function() {
    $('p').html($('li').html());
})

HTML

<p>text</p>
<ul id='ul'>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>

Upvotes: 0

Views: 64

Answers (3)

Joseph Cho
Joseph Cho

Reputation: 4214

Welcome to StackOverflow! Congrats on your first question.

You want this to target the element you've clicked instead using jQuery to find a li element like so:

$('li').click(function() {
    $('p').html($(this).html());
})

I've created a fiddle here: https://jsfiddle.net/o2gxgz9r/74708/

Upvotes: 1

Mamun
Mamun

Reputation: 68933

Use this to refer the currently clicked li. Also since you are trying to get/set the text content, I will suggest you to use text() instead of html():

$('li').click(function() {
    $('p').text($(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>text</p>
<ul id='ul'>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370739

$('li').html() will grab the HTML of the first matching li element. Use this instead, to refer to the li that was clicked on. But, since you aren't inserting HTML markup, but just plain text, it would be more appropriate to use the .text methods:

$('li').click(function() {
  $('p').text($(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>text</p>
<ul id='ul'>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

Or, if you wanted, no need to include a big library like jQuery for something as simple as this:

const p = document.querySelector('p');
document.querySelector('#ul').onclick = ({ target }) => {
  p.textContent = target.textContent;
};
<p>text</p>
<ul id='ul'>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

Upvotes: 2

Related Questions