Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ID of existing same class name element created dynamically

I already have some href anchors in my DOM like this:-

    <div id="outermenu">
        <a href="#" id="uniqueid1" class="myclassone">link</a>
        <a href="#" id="uniqueid2" class="myclasstwo">link</a>
    </div>

I am using jQuery to insert more href anchors, all of which use the same class name of only one other element on the page, so there will be two instances of the href with class "myclassone", only one of these will have the id "uniqueid1".

What I am looking to do when the dynamically inserted anchor elements are added to the DOM via another click method, find the anchors with the same class name and get the unique id attribute for each corresponding element with the same class name and print this in a div with id 'box'.

I have tried the following, to no avail.

$('this').each(function () {
    var anchorid = this.id;
    $("#box").html(anchorid);
});

Basically, how can I traverse through the DOM and find an elements ID inside the "outerid" div ID which has the same class name as a newly created element and subsequently display the elements ID?

Update: Thanks for the replies. I failed to mention that I am using this within the jquery autocomplete plugin by devbridge, which the docs state $this is bound to the input element.

I have therefore set up the autocomplete plugin like so:-

   var searchwordss = [
      { value: 'First Word', data: 'myclassone' }, 
....

Then using the data value to output:-

    var searchresults = '<a href="#" class="' + suggestion.data + '">Click here see more ' + suggestion.value + ' articles.</a>';
    $('#box').html(searchresults);

This generates:- Click here see more First Word articles.

I therefore need to get the ID for another purpose, the ID of the anchor element which already exists in the DOM and has class "myclassone" - bearing in mind this class name will change depending on the autocomplete search word selected. So, in my HTML example, $this is bound to "outermenu".

like image 349
Grant G Avatar asked Jan 25 '26 09:01

Grant G


1 Answers

To answer this in the OP's question -

What I am looking to do when the dynamically inserted anchor elements are added to the DOM via another click method, find the anchors with the same class name and get the unique id attribute for each corresponding element with the same class name and print this in a div with id 'box'.

$('#add').click(function(e) {
    e.preventDefault();
    $('a').each(function() {
        if( $(this).hasClass('myclassone') ) {
            $('#box').append(this.id);
        }
    });
});

This can be seen in action here - http://jsfiddle.net/jayblanchard/3473s/ All that is left to do is calculate a unique id and add the new element to the page.

like image 54
Jay Blanchard Avatar answered Jan 26 '26 23:01

Jay Blanchard