如何检查ul是否有给定文本的li
方法1:使用列表上的each()方法来检查innerText属性。
无序列表中的每个元素首先使用jQuery选择器进行选择。each()方法被用于这个列表的迭代。这个方法有一个回调函数,返回当前索引和迭代的元素。
返回的元素里面的文本被检查为innerText属性,看它是否与所需的文本相匹配。匹配成功意味着所选无序列表内的文本具有所需文本。
语法:
let found = false;
$("#list li").each((id, elem) => {
if (elem.innerText == requiredText) {
found = true;
}
});
return found;
示例:
<!DOCTYPE html>
<html>
<head>
<title>
Check if ul has li with a specific text in jQuery.
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to check if ul has li with
a specific text in jQuery?
</b>
<ul id="list">
<li>GeeksforGeeks</li>
<li>Computer</li>
<li>Science</li>
<li>Portal</li>
</ul>
<p>
The li elements contain the text "Computer":
<span class="output">
</span>
</p>
<p>
The li elements contain the text "Python":
<span class="output2">
</span>
</p>
<button onclick="runChecks()">
Check for the text
</button>
<script src="https://code.jquery.com/jquery-3.4.1.min.js">
</script>
<script>
function checkforText(requiredText) {
let found = false;
$("#list li").each((id, elem) => {
if (elem.innerText == requiredText) {
found = true;
}
});
return found;
}
function runChecks() {
ans1 = checkforText('Computer');
document.querySelector(".output").textContent = ans1;
ans2 = checkforText('Python');
document.querySelector(".output2").textContent = ans2;
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
方法2:使用contains()选择器。
contains()选择器用于选择具有与给定文本匹配的元素。这个文本可能存在于该元素的任何一个子代或该元素本身。它需要一个参数,即要匹配的区分大小写的文本。
contains() 选择器和用于选择列表元素的选择器一起使用。如果没有选择任何元素,也就是说,如果给定的文本不存在,返回的元素数将是0。可以用length属性检查返回的元素数,用来验证列表是否包含指定的文本。
语法:
let found = false;
selector = `#list :contains('{requiredText}')`
selectedList =(selector);
if (selectedList.length) {
found = true;
}
return found;
示例:
<!DOCTYPE html>
<html>
<head>
<title>
Check if ul has li with a specific text in jQuery.
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to check if ul has li with
a specific text in jQuery?
</b>
<ul id="list">
<li>GeeksforGeeks</li>
<li>Computer</li>
<li>Science</li>
<li>Portal</li>
</ul>
The li elements contain the text "Computer":
<span class="output">
</span>
The li elements contain the text "Python":
<span class="output2">
</span>
<button onclick="runChecks()">
Check for the text
</button>
<script src="https://code.jquery.com/jquery-3.4.1.min.js">
</script>
<script>
function checkforText(requiredText) {
let found = false;
selector
= `#list :contains('{requiredText}')`
selectedList =(selector);
if (selectedList.length) {
found = true;
}
return found;
}
function runChecks() {
ans1 = checkforText('Computer');
document.querySelector(".output").textContent = ans1;
ans2 = checkforText('Python');
document.querySelector(".output2").textContent = ans2;
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。