David
David

Reputation: 2721

how to get the text of an element like this using jquery?

there is a snippets of html codes like this<label for=name>fill in your name<span>*</span></label>, when using jquery $("label[for='name']").text(), it returned 'fill in your name*',how can get exactly 'fill in your name'?

Upvotes: 0

Views: 68

Answers (2)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174967

I would suggest you don't put the <span>*</span> and instead use pseudo-elements (:after). That way you can easily get better results.

See this EXAMPLE.

Note the cleaner markup:

<label for="name" class=required>Fill in your Name</label>

Every .required label will have the star by default thanks to the :after pseudo-element which is applied to it:

label.required:after {
    content: '*';
}

Important Note: The mentioned solution will fail on IE7 and below, as they do not support pseudo elements.

Upvotes: 1

Andy E
Andy E

Reputation: 344575

contents() allows you to select all node types - including just text nodes. For example, this will return the text for the first text node of the element:

$("label[for='name']").contents().eq(0).text();

Working demo: http://jsfiddle.net/mX8zK/

Upvotes: 1

Related Questions