Martin
Martin

Reputation: 2017

Javascript: How to change attributes of child elements?

I have this hidden link, which is needed for other purposes:

<span id="notitle" style="display: none;">
<a href="...Foo" title="Foo" style="..."></a>
</span>

The link is generated dynamically and automatically includes the title attribute. But I'd like to remove the title attribute since the value is copied when the user copy-pastes surrounding text.

I thought of using javascript. This is what I've got so far:

<html>
    <head>
        <script type="text/javascript">
          function notitle() {
            var mylist=document.getElementById("notitle")
            var listitems= mylist.getElementsByTagName("a")
            for (i=0; i<listitems.length; i++) {
              listitems.setAttribute("title", "");
            }
      }
        </script>
    </head>

<body onLoad="notitle()">

<p>Before hidden link:
<span id="notitle" style="display: none;">
<a href="#Foo" title="Foo">This Link should have no title attribute</a>
</span>
After hidden link.</p>
</body>
</html>

But doesn't work. I guess it's about listitems.setAttribute("title", ""); Any idea? Cheers :)

Upvotes: 1

Views: 11827

Answers (4)

o-o
o-o

Reputation: 8244

You're doing

listitems.setAttribute("title", ""); 

i times.

Add an array index into the list.

Upvotes: 0

Mario Menger
Mario Menger

Reputation: 5902

You need to add the i index:

listitems[i].setAttribute("title", "");

Upvotes: 0

peirix
peirix

Reputation: 37751

First of all, you need to select the one specific item by using listitems[i], second, I think you can do it as simple as this:

listitems[i].title = ""

Upvotes: 1

Evan Trimboli
Evan Trimboli

Reputation: 30082

listitems is the collection, so your code is probably throwing an error.

Anyway, you want:

listitems[i].setAttribute("title", "");

Upvotes: 4

Related Questions