简体   繁体   中英

getElementsByTagName doesn't work for my <a> tags

I can't get this to work:

    <p>
        <a href="#">First</a>
        <a href="#" id="hasID">Second</a>
        <a href="#">Third</a>
        <a href="#" id="someID">Fourth</a>
    </p>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

    <script>
        var link = document.getElementsByTagName("a");
        link.style.fontSize = '16px';
        link.style.textDecoration = 'none';
        link.style.color = '#333333';
        link.style.fontWeight = 'bold';
    </script>

I'm trying to add CSS styles ( font-size , text-decoration , color , font-weight ) to all the <a> tags of my HTML code.

This isn't working because you're trying to apply the changes to the list vs. the individual links. You need to loop through the links and apply the changes to the individual items

var all = document.getElementsByTagName("a");
for (var i = 0; i < all.length; i++) {
  var link = all[i];
  link.style.fontSize = '16px';
  link.style.textDecoration = 'none';
  link.style.color = '#333333';
  link.style.fontWeight = 'bold'
}

Additionally it looks like your script is running before the a elements are defined. Hence the getElementsByTagName will return an empty collection. Try moving the script to after the definition of the anchor elements

When the closing tag of that <script> block is encountered, the whole code in it is evaluated. Since anything after </script> has not been parsed yet, the result from document.getElementsByTagName('a') is not as expected.

Wrap the method in an onload or DOMContentLoaded event.

It seems that you want to target all anchor elements. Instead of looping through all anchorts, you'd better append a <style> element with the given CSS text:

window.addEventListener('load', function() {
    // `window.attachEvent('onload', function() {` for old IE versions
    var style = document.createElement('style');
    var cssText = 'a,a:link,a:visited {' +
             'font-size:16px;text-decoration:none;color:#333;font-weight:bold;}';
    style.appendChild(document.createTextNode(cssText));
    document.getElementsByTagName('head')[0].appendChild(style);
}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM