Retrieving shortcut content in jQuery

I am using jQuery for my application. In my code, I want to get only the text "Name" in the label.

I tried it with

$("#label"+div_id+"").html(); //but displays Firstname along with the span tag.. 

But I only need a name. How can i do this?

Below is my HTML code

  <label id="label1">Firstname<span class="req"><em> * </em></span></label> 
+4
source share
2 answers

A common solution to this problem is to get text, but not child text, - elem.clone().children().remove().end().text(); (here is $("#label"+div_id) ). This has the same result as the karim79 solution, but so as not to break if other tags are added to the label.

+6
source

Copy the element, free the EM, and finally remove the span (test) tag:

  var clone = $("#label"+div_id+"").clone(); clone.find('em').empty().remove('span'); alert(clone.text()); //alerts 'Firstname' 

I will say that @ozan's solution is the best (if a little less readable) and does this in only one line:

  alert($("#label"+div_id+"").clone().children().remove().end().text()); 
+5
source

Source: https://habr.com/ru/post/1286795/


All Articles