tags:

views:

321

answers:

2

Hi,

I am using JQuery for my application. In my code, I want to get only the text 'Firstname' in the label.

I tried it with

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

But I only need Firstname. How can i do so?

The following is my Html code

 <label id="label1">Firstname<span class="req"><em> * </em></span></label>
+4  A: 

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

    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 better one (if slightly less readable) and does it in just one line:

    alert($("#label"+div_id+"").clone().children().remove().end().text());
karim79
That will also get the * from the <em>.
Jarrod Dixon
alert($("#label"+div_id+"").text()); displays Firstname along with the * in it .But i need Firstname alone..How can i do so?
Aruna
Editing my answer
karim79
@Aruna see my edit
karim79
clone.text() displays Firstname * ...I dont want this * to be displayed
Aruna
@Aruna - edited my answer. Tested the solution, it now returns exactly 'Firstname'
karim79
+3  A: 

The general solution to this problem -- namely, getting immediate text but not child text -- is elem.clone().children().remove().end().text(); (where elem here is $("#label"+div_id)). This has the same result as karim79's solution but with the benefit of not breaking if other tags are added to the label.

ozan