'Trying to pull H3 text using JS
I am trying to create a Google tag manager JS variable to pull the article name when someone clicks on it.
I need to pick up just the title (in red) but not " Home Sellers "
document.getElementsByClassName("blog-listing-post__summary blog-listing-post__summary--big")[0].querySelector("H3").innerText
returns:'HOME SELLERS\nWhich Home Appliances are Included with a Sold Property?'
How can I skip "home sellers" and pull value just under?
Thank you!
Solution 1:[1]
Try using the split() and slice() methods. This will return an array that you can reference.
let x = 'HOME SELLERS\nWhich Home Appliances are Included with a Sold Property?';
let y = x.split('\n').slice(1);
console.log(y);
console.log(y[0]);
Solution 2:[2]
const h3 = document.querySelectorAll('h3').at(-1).innerText
Solution 3:[3]
If you want all and only the top level text, you just need to filter the H3's childNodes to get only text nodes and then join all the text together. The solution below should work in most cases.
const myHeadline = document.getElementsByTagName('h3')[0];
const myHeadlineTopLevelText = [...myHeadline.childNodes].filter(node=> node.nodeType === 3).map(node=>node.textContent).join("").trim();
console.log(myHeadlineTopLevelText);
<h3>
<span>sub text</span>
Main text
</h3>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter |
| Solution 2 | Vladyslav Yukhanov |
| Solution 3 | Neil VanLandingham |

