如何获取子节点值;改变价值

时间:2011-09-12 02:38:46

标签: javascript parent-child traversal getelementsbytagname getelementsbyclassname

如何使用JavaScript(无JQuery)遍历具有公共类的一堆DIV,然后根据值检查<span>标记内的值,将href值更改为其他值。这是一个标记示例。

<div class="module-content">
<div class="js-tab-content S00">
    <h2 class="heading">
        <a href="http://someurl.com">
            <span>Adelaide</span>
        </a>
    </h2>
</div>
<div class="js-tab-content N00">
    <h2 class="heading">
        <a href="http://anotherurl.com">
            <span>Sydney</span>
        </a>
    </h2>
</div>
<div class="js-tab-content V00">
    <h2 class="heading">
        <a href="http://thisurl.com">
            <span>Melbourne</span>
        </a>
    </h2>
</div>
</div>

2 个答案:

答案 0 :(得分:1)

var tabContentDivs = document.getElementsByClassName("js-tab-content");

for (var i = 0, tabContentDiv; tabContentDiv = tabContentDivs[i]; ++i) {
    var spanEl = tabContentDiv.querySelector(".heading span");
    var spanText = spanEl.innerText;

    var aEl = tabContentDiv.querySelector(".heading a");
    aEl.href += "#" + spanText; // for example
}

答案 1 :(得分:1)

这是:

var divs = document.getElementsByClassName("js-tab-content");
for(var i=0;i<divs.length;i++){
    var div = divs[i];
    if(!div) break;
    var span = div.getElementsByTagName("span");
    var link = div.getElementsByTagName("a");
    if(span[0].innerHTML == "Adelaide") link[0].href = "http://google.com";
}