简体   繁体   中英

Change href of <a> element using javascript

Please, code to change domain in href (html, JavaScript).

Exemple:

<a id="NewL" href="http://exemple.com/indice.html">Indice</a>

To:

<a id="NewL" href="http://exemple.net/indice.html">Indice</a>

Exemple code not working:

<script  type = "text/javascript" >
function replace() {
    var aEls = document.getElementById('NewL').getElementsByTagName('a');
    aEls.href = aEls.href.replace('http://exemple\.com', 'http://exemple\.net');
}
</script>

Thanks, @t.niese:

<a id="NewL" href="http://exemple.com/indice.html">Indice</a>

<script  type="text/javascript" >
function replace() {
    var aEl = document.getElementById('NewL');
    aEl.href = aEl.href.replace('http://exemple.com', 'http://exemple.net');
}
replace();
</script>

Please help me, not change in various ID in same page:

   <a id="NewL" href="http://exemple.com/indice.html">Indice</a>
   <a id="NewL" href="http://exemple.com/indice2.html">Indice 2</a>

    <script  type="text/javascript" >
    function replace() {
        var aEl = document.getElementById('NewL');
        aEl.href = aEl.href.replace('http://exemple.com', 'http://exemple.net');
    }
    replace();
    </script>

Element.getElementsByTagName() :

[...]The subtree underneath the specified element is searched, excluding the element itself.[...]

so you search for the elements with the tag name a within your element with the id NewL

Because document.getElementById('NewL') is already your a element, you won't need the getElementsByTagName('a') , as of that you should only write:

 var aEl = document.getElementById('NewL');

Also your replace is wrong, you don't need to escape the . if you pass the search as string.

 aEl.href = aEl.href.replace('htp://exemple.com', 'htp://exemple.net');

Beside that Element.getElementsByTagName() returns a list of elements, so even if your search would have been correct, you would need to use a loop to iterate through that result.

change your javascript to the following:

<script  type = "text/javascript" >
function replace() {
    var aEl = document.getElementById('NewL');
    aEl.href = aEl.href.replace('htp://exemple\.com', 'htp://exemple\.net');
}
</script>

You already selected the element by the getElementById no need to find the a class in it. Also you mispelled the variable which I changed to aEl

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