How do I add target=“_blank” to a link within a sp

2019-01-05 00:19发布

Let's say I have the following code:

<div id="link_other">
    <ul>
        <li><a href="http://www.google.com/">google</a></li>
        <li>
            <div class="some_class">
                dsalkfnm sladkfm
                <a href="http://www.yahoo.com/">yahoo</a>
            </div>
        </li>
    </ul>
</div>

In this case, the JavaScript would add target="_blank" to all links within the div link_other.

How can I do that using JavaScript?

7条回答
聊天终结者
2楼-- · 2019-01-05 00:56

Non-jquery:

// Very old browsers
// var linkList = document.getElementById('link_other').getElementsByTagName('a');

// New browsers (IE8+)
var linkList = document.querySelectorAll('#link_other a');

for(var i in linkList){
 linkList[i].setAttribute('target', '_blank');
}
查看更多
登录 后发表回答