jQuery 怎么根据内容来获取元素?

江河/ 2023年07月30日/ JavaScript/ 浏览 705

<div>hello</div>
<script>
    const str = 'hello';
    // const el = ?
</script>


如何才能获取内容包含 hello 的元素呢?


方法一


const str = 'hello';
const elArr = $(`div:contains(${str})`); // elArr是个数组


elArr 会包含所有包含 hello 的元素。


比如,结构如下:


<div>
	<div>
		<div>
			hello
		</div>
	</div>
</div>


elArr 中就会包含 3 个元素。


方法二


let str = 'hello';
let el = {}; 
const elArr = $('div');
for (let index = 0; index < elArr.length; index++) {
  const element = elArr[index];
  if ($(element).text() === str) {
    el = element;
    break;
  }
}

console.log(el)


这种方法在获取到第一个符合条件的元素就中断了。


实际开发中需按自己的需求跳转代码。


发表评论

暂无评论,抢个沙发...

客服 工单