SearchForKnowledge
SearchForKnowledge

Reputation: 3751

How to get the first occurrence of text inside a DIV

I have the following HTML:

<div class="provInfoSub hidOverflow floatLeft vertAlignT">
    <specialty><a title="Plastic Surgery" href="check.aspx">Plastic Surgery</a></specialty>
    <br />
    <specialty2><a title="Hand Surgery" href="check2.aspx">Hand Surgery</a></specialty2>
</div>

How can I, using JQuery, retrieve only the first text entry, "Plastic Surgery" by stripping away all the HTML/XML code outside of it

Upvotes: 0

Views: 156

Answers (3)

Artūras
Artūras

Reputation: 473

in case several speciality tags

 $('specialty').first().text();

or even better

 $('specialty a').first().text();

Upvotes: 2

Hackerman
Hackerman

Reputation: 12305

Something like this:

$(function(){
var valor = $("specialty a").html();
alert(valor);
});

Working fiddle: http://jsfiddle.net/7uohabuw/

Upvotes: 1

James Donnelly
James Donnelly

Reputation: 128791

Seeing as you only have one specialty node, you can simply pull its text():

$('specialty').text();
-> "Plastic Surgery"

If this truly is HTML it's worth noting that specialty and specialty2 are not valid HTML elements and would fail HTML validation, so you may want to consider changing those. If those are your only specialty and specialty2 elements, you could assign those as id attributes:

<div id="specialty">...</div>
<div id="specialty2">...</div>

And then pull the text using an ID selector instead:

$('#specialty').text();

Upvotes: 2

Related Questions