0

如何获得红色跨度<a>之后的-tag的标签内部文本?

这是示例源代码:

<p>
    Text1<br>
    <span style="color:blue">span</span><br>
    <a href="http://google.com">Google</a>
</p>
<p>
    Text1<br>
    <span style="color:red">span</span><br>
    <a href="http://bing.com">Bing</a>
</p>
<p>
    Text1<br>
    <span style="color:blue">span</span><br>
    <a href="http://facebook.com">Facebook</a>
</p>
    <p>
    Text1<br>
    <span style="color:red">span</span><br>
    <a href="http://myspace.com">myspace</a>
</p>

这是输出

在此处输入图像描述

我尝试使用 document.get.Element.ByTagName,但我真的不知道如何将它用于仅在红色“span”之后跟随的元素。

也许,我应该使用 jQuery?

4

1 回答 1

1

如果你要使用类,而不是内联 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 小提琴演示

于 2013-09-22T17:55:43.653 回答