Sunil Chaudhry
Sunil Chaudhry

Reputation: 263

Get text of an element before its containing span tag in jQuery

I want the text in 2 variables like :

var a = "Bar" ;   
var b = "by year" ;

Html:

<h5 class="heading">Bar<span class="cT">by year</span></h5>

Upvotes: 0

Views: 518

Answers (4)

HMR
HMR

Reputation: 39260

Assuming h5 only has 2 nodes that contain text.

You could try the following (no jQuery needed only to create the html element)

var $content = $(`
<h5 class="heading">
  Bar
  <span class="cT">
    by year
  </span>
</h5>`);
var [a,b] = 
  []
  .map.call(
    $content[0].childNodes
    ,x=>x.textContent
  )
  .map(x=>x.trim())
  .filter(x=>x!=="")
;
alert("a is:"+a);
alert("b is:"+b);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

gil.fernandes
gil.fernandes

Reputation: 14611

This is another option to solve this problem:

let a = jQuery(".heading").clone().find('span').remove().end().text();

let b = jQuery(".heading > span").text()

Regarding a a clone is performed and then the span is removed from the clone and the text of the manipulated clone is captured.

Regarding b the text of the direct span child of .heading is extracted.

Upvotes: 0

guest271314
guest271314

Reputation: 1

You can use destructuring assignment to get .firstChild and .textContent properties of .heading .childNodes

let {0: {textContent: a}, 1: {firstChild: {textContent: b}}} = document.querySelector(".heading").childNodes;

console.log(`a:${a}, b:${b}`);
<h5 class="heading">Bar<span class="cT">by year</span></h5>

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

For first variable, You can get the text node using:

var a = $('.heading').contents().filter(function() {
 return this.nodeType === Node.TEXT_NODE; 
}).text();

for second element:

var b = $('.ct').text();

Upvotes: 3

Related Questions