简体   繁体   中英

How add ID to HTML href with javascript

I have an HTML like this

<div class="this">
   <a href="exp.com">EXP</a>
</div>

I want to add id to <a> . But do not know what to do.

If you want to add this with Javascript, you'll need to use a selector to target your <a> tag and then set the id attribute on it. You can do this by using the querySelector() function or as seen below:

// Find an <a> tag that occurs below a class called "this" and set its id attribute
document.querySelector('.this > a').id = "some-id";

There are many other available functions to handle this through native Javascript and other frameworks, so your milage may vary depending on what you are using.

Example

In this example, we have provided some CSS that should only apply to an element with an id of "test" and we'll run the necessary code to show that the id is being added to the element (as it will be red):

 document.querySelector('.this > a').id = 'test';
 #test { color: red; }
 <div class="this"> <a href="exp.com">EXP</a> </div>

First select your element using something like .getElementsByClassName() . Keep in mind that .getElementsByClassName() returns a NodeList collection of elements, so you'll want to access the first index (or loop over them). You can then simply set the ID with .id , as the ID is merely a property of an element.

This can be seen in the following:

 const element = document.getElementsByClassName('this')[0]; element.id = 'element'; console.log(element);
 <div class="this"> <a href="exp.com">EXP</a> </div>

Add the id attribute to the <a> tag. See the differences of the middle line:

<div class="this">
   <a id="expid" href="exp.com">EXP</a>
</div>

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