[英]I am trying to dynamically pull all <h3> elements from xhtml file and put them in a selection list using javascript
[英]Trying to pull H3 text using JS
尝试使用 split() 和 slice() 方法。 这将返回一个您可以引用的数组。
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]);
const h3 = document.querySelectorAll('h3').at(-1).innerText
如果您想要所有且只有顶级文本,您只需要过滤 H3 的 childNodes 以仅获取文本节点,然后将所有文本连接在一起。 下面的解决方案应该适用于大多数情况。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.