Search code examples
javascriptparent-childtraversalgetelementsbytagnamegetelementsbyclassname

How to get childnode value & change value


How can I use JavaScript (no JQuery) to traverse through a bunch of DIVs that has a common class, then check the value within the <span> tag, base on the value, change the href value to something else. Here is an example mark-up.

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

Solution

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