Javascript瞄准一个表,该表位于包含特定文本的H1之后
Javascript to target a table that comes after an H1 containing specific text
我想只在包含'编辑共享区域'的H1之后才针对表
这是显示我想要的目标表的html:
<h1>Editing Shared Regions</h1>
<ul class="smartbar">
<li class="selected"><a href="/core/apps/content/page/?id=-1">Regions</a></li>
</ul>
<table>
<thead>
<tr>
<th>Region</th>
<th>Type</th>
<th>Items</th>
<th class="action"></th>
<th class="action"></th>
</tr>
</thead>
<tbody>
您可以使用:contains()
,一般兄弟选择器~
$("h1:contains('Editing Shared Regions') ~ table")
.css("color", "blue")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Editing Shared Regions</h1>
<ul class="smartbar">
<li class="selected"><a href="/core/apps/content/page/?id=-1">Regions</a>
</li>
</ul>
<table>
<thead>
<tr>
<th>Region</th>
<th>Type</th>
<th>Items</th>
<th class="action"></th>
<th class="action"></th>
</tr>
</thead>
<tbody>
</table>
下面是一个不使用jQuery的示例。我不应该扩展DOM,但是编写像guest271314的例子这样的一行代码会很有趣。
NodeList.prototype.contains = function(searchText) {
for (var ix = 0; ix < this.length; ix++) {
if (this.item(ix).innerText.trim() === searchText) {
return this.item(ix);
}
}
return null;
}
Node.prototype.findNext = function(tag) {
var el = this;
while (el.nextSibling) {
el = el.nextSibling;
if (el.tagName && el.tagName.toUpperCase() === tag.toUpperCase()) {
return el;
}
}
return null;
}
document.querySelectorAll('h1').contains('Editing Shared Regions').findNext('table').style.color = 'red';
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>
<div class="container">
<h1>A Heading</h1>
<table>
<tr>
<td>This is not the table you're looking for</td>
</tr>
</table>
<h1>Editing Shared Regions</h1>
<ul class="smartbar">
<li class="selected"><a href="/core/apps/content/page/?id=-1">Regions</a></li>
</ul>
<table>
<thead>
<tr>
<th>Region</th>
<th>Type</th>
<th>Items</th>
<th class="action"></th>
<th class="action"></th>
</tr>
</thead>
<tbody>
<tr>
<td>PNW</td>
<td>Land</td>
<td>meow</td>
<td>x</td>
<td>y</td>
</tr>
</tbody>
</table>
</div>
相关文章:
- 无法将包含文本和图像的SVG保存到画布
- 检查选择器在jQuery中是否包含文本(即不是媒体)
- jQuery 隐藏按钮,如果它们不包含文本
- 创建包含文本内容的新 Google 云端硬盘文件 (javascript)
- 使用XPath选择包含文本的节点,而不考虑CasperJS中的空白
- CKEDITOR-将粗体应用于包含数字的编号列表
- 使用DOM javascript包含文本和图片的按钮
- 若文本框中包含文本,则不允许用户离开页面
- 如果其他字段包含文本,则阻止文本字段
- 时刻.js以日期中间格式包含文本
- 检查文本框是否包含文本,如果包含,则发送
- Javascript/jQuery,将CSS应用于包含特定文本/html的元素
- 使用 jquery 专注于引导文本区域
- 如何 chk 如果 span 标签是否包含文本
- 将包含文本框的 HTML 表转换为具有文本框值的 HTML 表
- 如何加载仅包含文本内容的 iFrame
- 将拖放链接拖放到仅包含文本的文本框中
- 将自动完成应用于包含数据库中数据的动态生成的文本框
- 包含文本和 URL 的图像列表视图
- 检查 span 元素是否包含“文本”,并且是父元素的最后一个子元素