MyWherany
MyWherany

Reputation: 39

Find innerText after an element

HTML

<div class="price"><strike>AAA</strike>BBB</div>

My question is if there is any way to grab only the "BBB" text, using JS. Note that I don't have any access to the HTML code.

I need to grab both texts (AAA and BBB) separately.

For example document.querySelector('.price strike').innerText which returns "AAA"

For the second part I use document.querySelector('.price').innerText which will returns "AAABBB". That's the problem. Is there any way to select directly the "BBB"?

Upvotes: 1

Views: 917

Answers (3)

cccn
cccn

Reputation: 949

I'm not sure if there is any method to get this 'no strike' text directly, but you can achieve what you want with a little workaround. For example playing with the slice and indexOf methods:

const strikeText = document.querySelector('.price strike').innerText;
const allText = document.querySelector('.price').innerText;

const restText = allText.slice(allText.indexOf(strikeText) + strikeText.length)

console.log(strikeText)
console.log(restText)
<div class="price"><strike>AAA</strike>BBB</div>

Upvotes: 1

ControlAltDel
ControlAltDel

Reputation: 35011

Iterate over the child nodes and add node values from text nodes

function getNodeText(elem) {
  var txt = "";
  for (let i = 0; i < elem.childNodes.length; i++) {
    if (elem.childNodes[i].nodeType === 3) { //text node
      txt += elem.childNodes[i].nodeValue;
    }
  }
}

Upvotes: 0

Abbas Hosseini
Abbas Hosseini

Reputation: 1643

in your specific case 'BBB' is the last child of '.price' so you can get it's value as simple as:

const text = document.querySelector('.price').lastChild.nodeValue;
document.querySelector('#result').innerHTML = text;
<div class="price"><strike>AAA</strike>BBB</div>
<div id="result"></div>

Upvotes: 4

Related Questions