如何在指定项目后使用getElementById获取内部标记?

时间:2013-09-22 17:49:59

标签: javascript jquery html

如何获取<a>的标记内部文字 - 在红色范围之后的下一个标记?

以下是示例源代码:

<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>

这是输出

enter image description here

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

也许,我应该使用jQuery?

1 个答案:

答案 0 :(得分: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 Fiddle demo

当然,在大多数现代浏览器中,如果你使用类名(再次使用而不是内联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 Fiddle demo