0

How do I get the "grab me" text in HTML using vanilla javascript? I have some thoughts below, but I am looking for a better way.

HTML

<div>
    <h1>H1 here</h1>
    grab me
</div>

Javascript

let firstSetString = document.querySelector("h1").innerHTML;
let BothSetString = document.querySelector("div").innerText.replace("\n","")
let secondSetString = BothSetString.replace(firstSetString,"")
console.log(secondSetString)// returns grab me
Francis
  • 21
  • 3
  • @pilchard seems to be jquery. Im looking for just plain javascript. Will refer to the link if I will use jquery. Thank you. – Francis Aug 26 '21 at 10:19
  • 1
    There are multiple answers that are vanilla js that propose the same solution as the answer you accepted here. The accepted answer often isn't the best answer, especially for older questions. – pilchard Aug 26 '21 at 10:25

2 Answers2

1

The div has 3 child nodes: a text node, an h1 node, and another text node. The last child node contains the text to grab:

const div = document.body.querySelector("div");
const text = div.childNodes[div.childNodes.length - 1].textContent;
console.log(text.trim());
<div>
  <h1>H1 here</h1>
  grab me
</div>
kol
  • 27,881
  • 12
  • 83
  • 120
0

Use regular expression

const div = document.querySelector("div");
const texts = div.innerHTML.split(/\r|\r\n|\n/);
console.log(texts[2].trim());
<div>
    <h1>H1 here</h1>
    grab me
</div>

Use childNodes to filter


const div = document.querySelector("div");

for(let i = 0; i < div.childNodes.length; i++){
  const childNode = div.childNodes[i];
  if(isEmpty(childNode.nodeValue) && childNode.nodeName == '#text'){
    console.log(childNode.nodeValue.trim());
  }
}

function isEmpty(val){
  return val ? val.trim() : true;
}
<div>
    <h1>H1 here</h1>
    grab me
</div>
Ian
  • 1,198
  • 1
  • 5
  • 15