简体   繁体   中英

Why doesn't my statement change and add attributes for anchor tag?

I'm trying to change the value of anchor tag and also add new attributes but it does not seem to work.

document.getElementsByClassName('button')[0]
  .getElementsByTagName('a')[0]
  .attr({ 
    href: '#', 
    data: 'xyz', 
    name: 'test'
  });

The problem is that you're attempting to use a jQuery method on a native DOM element. My guess is that your browser's throwing an error indicating such.

Instead, use jQuery syntax to create an actual jQuery object:

$('.button a').attr({ ... });

This has the bonus benefit of being a fraction as long.

In case you actually need to select the first of the elements jQuery grabs with that selector, use first() :

$('.button a').first().attr({ ... });

This filters the jQuery object into a new one without converting to a native DOM element. It's fragile, however, because it depends on your markup for accurate selection. I'd prefer to add another class to that button or target an ancestor element for specificity:

$('.button.my-extra-class a').attr({ ... });

I've put together an example of how you can set attributes.

 let link = document.getElementsByTagName('a')[0]; link.setAttribute("href", "http://www.google.com"); link.setAttribute("data", "xyz"); link.setAttribute("data-name", "test"); 
 <ul> <li> <a href="#">A link</a> </li> </ul> 

https://codepen.io/anon/pen/vaNZKd

Here's some more info on setting attributes: https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute

$("button")
    .first()
    .find("a")
    .first()
    .attr('href', '@')
    .attr('data', 'xyz')
    .attr('name', 'test');

What this means is that you're getting the first <button> , then the first <a> within that button, and then assigning the data.

Based on your code, I assume this is what you want.

You can try querySelectorAll

  let anchor = document.querySelectorAll('a.button')[0]; anchor.setAttribute("href", "http://www.google.com"); 
  <a href="#" class="button">A link - will be affected</a><br/> <a href="#" class="button">B link - not affected</a><br/> <a href="#">C link - not affected</a><br/> <a href="#">D link - not affected</a><br/> 

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