如果你要使用类,而不是内联 CSS,你可以只使用 CSS:
.redStyle = {
color: red;
}
.blueStyle {
color: blue;
}
// style the elements:
.redStyle + br + a, /* multiple adjacent-sibling combinators are required
if you insist on retaining the 'br' elements */
.redStyle ~ a {
color: green;
}
当然,这需要 HTML,例如:
<p>
Text1<br>
<span class="blueStyle">span</span><br>
<a href="http://google.com">Google</a>
</p>
<p>
Text1<br>
<span class="redStyle">span</span><br>
<a href="http://bing.com">Bing</a>
</p>
要使用 JavaScript 获取实际节点或这些节点的属性:
function follows(target, cName) {
while (target.previousSibling) {
if (target.previousSibling.className && target.previousSibling.className.indexOf(cName) > -1) {
return true;
} else {
target = target.previousSibling;
}
}
return false;
}
var links = document.getElementsByTagName('a'),
relevantLinks = [],
relevantText = [];
for (var i = 0, len = links.length; i < len; i++) {
if (follows(links[i], 'redStyle')) {
// this adds to the store of relevant links in which you're interested
relevantLinks.push(links[i]);
// you could act on them directly, but storing them
// allows for further use at a later time (if required)
}
}
for (var i = 0, len = relevantLinks.length; i < len; i++) {
// iterating over the relevant links/elements, pushing their text
// into another array to store that text
relevantText.push(relevantLinks[i]['textContent' || 'innerText']);
}
console.log(relevantText);
JS 小提琴演示。
当然,在大多数现代浏览器中,如果您确实使用类名(同样,而不是内联 CSS),您可以简单地使用document.querySelectorAll()
来检索相关元素的 nodeList,并直接对其进行迭代:
var links = document.getElementsByTagName('a'),
relevantLinks = document.querySelectorAll('.redStyle ~ a'),
relevantText = [];
for (var i = 0, len = relevantLinks.length; i < len; i++) {
relevantText.push(relevantLinks[i]['textContent' || 'innerText']);
}
console.log(relevantText);
JS 小提琴演示。