views:

35

answers:

3

I'm struggling to decipher a way to remove several specific href elements which contain no IDs and are children of individual parents with no IDs.

The best I can manage is identifying the four offending, out of 8 or 9 href tags (and the number may vary), by a specific word within the URL itself. For this, I do the following:

<script language=javascript>
var xx = document.getElementById('theID').getElementsByTagName('a');
var ptn=/\=media/;
for(var i=0; i<xx.length; i++) {
    if(ptn.exec(xx[i])){
    alert(xx[i]);
    }
}
</script>

Of course all this gives me is the four specific URLs within the href where "=media" is present. Now, somehow, I need to be able to remove either these href elements, or their parent elements (which happen to be unordered list tags). It's not until I get a level higher (table cell) that I gain access to an element ID, or anything distinguishing besides a particular word within the URL itself.

I'm open to any approach at this point - PHP may be an option (I really haven't explored this yet), but for this, javascript was my first logical choice. I can't tamper with the page that generates the links directly, only a secondary page which gets included at page load time.

Any pointers on how to solve this??

======================== final solution =====================

<script language=javascript>
var xx = document.getElementById('theID').getElementsByTagName('a');
var ptn=/\=media/;
for(var i=0; i<xx.length; i++) {
    while(ptn.exec(xx[i].href)){
        alert(xx[i]);
        xx[i].parentNode.removeChild(xx[i]);
    }
}
</script>
A: 

You don't need the ID to remove an element. You only need a reference to the element (which you seem to have).

instead of this:

alert(xx[i]);

try this:

XX[i].parentElement.removeChild(xx[i]);
Gabriel McAdams
Brilliant! I was close a time or two, but couldn't get to the finish line.
Adam
I'm glad you got it working. Don't forget to use Andy E's suggestion of using the href property in your regex test.
Gabriel McAdams
+1  A: 

You can call removeChild() on the parent element, like so:

xx[i].parentNode.removeChild(xx[i]);

As a side note, your regular expression isn't being executed on the href property. Change your if statement to:

if(ptn.exec(xx[i].href)){
Andy E
Good point - I've updated accordingly. Also, seems executing in an "if" is problematic - I've switched to "while" and get the results I was anticipating.
Adam
A: 
var parent = xx[i].parentNode;
parent.removeChild(xx[i]);

http://www.onlinetools.org/articles/unobtrusivejavascript/chapter2.html has some nice examples of similar operations (scroll down).

Tim
*removeNode()* is a proprietary method and isn't implemented in all browsers. Stick with *removeChild()*.
Andy E
@Andy - yes, just looked that up and confirmed. Edited my answer.
Tim