Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I grab an element with jQuery without a way to reference it via class, ID, etc

I have a table like so:

<table>
<thead>
    <tr>
        <th>Hostname</th>
        <th>Action</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>127.0.0.1</td>
        <td><a name="delete" onclick="remove_host('127.0.0.1')">Remove</a></td>
    </tr>  
    <tr>
        <td>127.0.0.2</td>
        <td><a name="delete" onclick="remove_host('127.0.0.2')">Remove</a></td>
    </tr>  
    <tr>
        <td>127.0.0.3</td>
        <td><a name="delete" onclick="remove_host('127.0.0.3')">Remove</a></td>
    </tr>
</tbody>

What I'm trying to do is, when a user clicks on Remove, that the link is replaced with one of those loading images so the user can't repeatedly hit the link.

How do I get the a element, so to speak, so I can set the HTML accordingly with jQuery?

On other parts of the site, I'm able to attach a rel="host-1" (or similar) to the link, so I can easily reference it to change out the HTML.

like image 724
Kyle Anderson Avatar asked May 16 '11 19:05

Kyle Anderson


2 Answers

$('a[name="delete"]').click(function() {

});

EDIT

Don't use inline JS. writing the following is much cleaner.

$('a[name="delete"]').click(function() {
    var thehost = $(this).parent().prev().html();
    remove_host(thehost);
});
like image 21
PeeHaa Avatar answered Oct 10 '22 11:10

PeeHaa


You can use the attribute selector to select based upon name of the <a/>

Also, you can use one() so the handler only fires once.

$("a[name='delete']").one("click", function(){
   $(this).html("Doing something...")
});

Example on jsfiddle

side note, just replacing with.html() will not remove the inline js, you could use .replaceWith() to completely remove the <a/>

$("a[name='delete']").one("click", function() {
    $(this).replaceWith($("<img/>").attr({src: "http://placekitten.com/g/50/50"}))
});

Example on jsfiddle

like image 160
Mark Coleman Avatar answered Oct 10 '22 09:10

Mark Coleman