roi roi - 3 months ago 9
jQuery Question

Get content without the content of child elements

how can i get the "li" text without the "span" content?

HTML

<ul class="texts">
<li>jimbo <span>Add text</span></li>
<hr />
<li>mary jane <span>Add text</span></li>
<hr />
<li>bill clinton <span>Add text</span></li>
</ul>


JS:

$(document).on('click','.texts li span',function() {
var current_content = $("#addReply textarea").val();
var chosen_content = $(this).parent("li").html();
$("#addReply textarea").val(current_content + "\n" + chosen_content)
});

Answer

If you want the contents without just the span that was clicked, you can use contents and not (and text rather than html, because it returns the text of all of the entries in the set you call it on [unlike html, which only returns the HTM of the first entry in the set]):

var chosen_content = $(this).parent("li").contents().not(this).text();

Example:

$(document).on('click', '.texts li span', function() {
  var current_content = $("#addReply textarea").val();
  var chosen_content = $(this).parent("li").contents().not(this).text();
  $("#addReply textarea").val(current_content + "\n" + chosen_content)
});
<ul class="texts">
  <li>jimbo <span>Add text</span>
  </li>
  <hr />
  <li>mary jane <span>Add text</span>
  </li>
  <hr />
  <li>bill clinton <span>Add text</span>
  </li>
</ul>
<div id="addReply">
  <textarea cols=40 rows=5></textarea>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Comments