Home > Software engineering >  Using Jquery to append to all href and src attributes
Using Jquery to append to all href and src attributes

Time:02-16

I need to append the name of my github repository to the beginning of all href and src attributes. Any help is appreciated.

<script>
  $(document).ready(function() {
    $(src).attr('src', '/Demo_App').each();
    $(href).attr('href', '/Demo_App').each();
});
</script>

CodePudding user response:

  1. Select all nodes on the DOM with
document.getElementsByTagName('*')
  1. Loop through them. If has src, update the src with repo name in front. If href, do the same thing but with the href instead.

const repoName = '/Demo_App';

window.addEventListener('load', () => {
    const all = document.getElementsByTagName('*');

    for (const node of all) {
        const src = node.getAttribute('src');
        const href = node.getAttribute('href');

        if (src) node.setAttribute('src', `${repoName}${src}`);
        if (href) node.setAttribute('href', `${repoName}${href}`);
    }
});
<body>
    <a href="https://google.com"></a>
    <img src="https://google.com" />
    <a href="https://google.com"></a>
    <img src="https://google.com" />
    <a href="https://google.com"></a>
    <img src="https://google.com" />
    <a href="https://google.com"></a>
    <img src="https://google.com" />
</body>

CodePudding user response:

use jQuery's attr() with a callback function to append values.

For example

const suffix = "/Demo_App";

// all elements with `src` attribute
$("[src]").attr("src", (_, src) => src   suffix)

// all elements with `href` attribute
$("[href]").attr("href", (_, href) => href   suffix)

As always you might not need jQuery

const suffix = "/Demo_App";

document.querySelectorAll("[src]").forEach(elt => {
  elt.src  = suffix
})

document.querySelectorAll("[href]").forEach(elt => {
  elt.href  = suffix
})
  • Related