简体   繁体   中英

JS: Add link dynamically to all elements of certain class

I work in a system where we have these elements representing a part of an audio clip, and a timeline for the audio that is browsable (click around to play different parts). However, the elements representing the parts of the audio clip does not actually link to the parts of the audio.. (so no "click this to play this part").

I have deducted that it is possible to link to a specific part of the call via for example: http://thelink.com/timeline?startms=%221600326183999%22 . And that the elements all have an attribute called "startms", for example:

<div class="segment-item" startms="1600326183999"></div>

Is there any way I could loop through all the elements in the page with the class "segment-item" and add a href="" with the value of their individual "startms" value to the link ( http://thelink.com/timeline?startms=%22TheValueHere%22 ).

Then finally, since I cannot build an addon to my browser for this, would it be possible to make a snipped which can be pasted into the console for easy use when I need it? Any other suggestions to making such a thing be easily accessible for usage without making or using an addon for chrome?

If you want to add the link to the element, you should add it like that

const elements = document.getElementsByClassName("segment-item")
    for (element of elements) {
        const a = document.createElement("a")
        a.href = `http://thelink.com/timeline?startms=%22${element.getAttribute("startms")}%22`
        a.innerText = "LINK NAME"

        element.appendChild(a)
    }

Adding a link based on element properties goes like this

const elements = document.getElementsByClassName("segment-item")
for (element of elements) {
    element.innerHTML = `<a href="http://thelink.com/timeline?startms=%22${element.getAttribute("startms")}%22">
                              Link name
                         </a>`
}

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