Tags
Asked 3 years ago
10 Jun 2021
Views 392
Imani

Imani posted

Using .text() to retrieve only text not nested in child tags


<div>Username : <span>Test </span></div>

in above code i just wnat to get the Username not its child element text also which is Test in our case

$("div").text()

text() of Jquery give me "Username: Test" which is not needed as per my requirment
kord

kord
answered Jun 10 '21 00:00

HTML CODE :

 <div class="field">Username : <span>Test </span></div>

if want to retreive text of parent not from children than remove children and get the text after but by remove function it will remove from dom . so without effecting current html , make clone of the current dom structure and remove all children and get text after that so following is the code :


 var text =$(".field").clone().children().remove().end().text();
console.log(text);

will print "Username :"

or use this simplified code

var cloned =$(".main").clone();  //make clone of the element 
$(cloned).children().remove(); // remove all children
var text=$(cloned).text(); //get the text
console.log(text)

will print same at console : "Username :"
Post Answer