APAD1
APAD1

Reputation: 13666

How to get title attribute from link within a class with javascript

I am trying to pull the title attribute from links within a class and having a bit of trouble:

<div class="menu">
<a href="#" title="4242" onclick="cselect()">United States</a>
<a href="#" title="4243" onclick="cselect()">Canada</a>
</div>

And here's what I've tried:

function cselect(){
    var countryID = $(this).attr("title");
    location.href = location.href.split("#")[0] + "#" +countryID;
    location.reload();
}

Thanks!

Upvotes: 1

Views: 3389

Answers (3)

feeela
feeela

Reputation: 29932

You must refer to the clicked element. One way is to pass this, as tymeJV suggested.

But I would set the event handler from a separate script block and just refer to the current element. For both of the following two solutions no additional inline onclick attribute is required.

/* using jQuery */
jQuery( '.menu a' ).on( 'click', function( event ) {
    event.preventDefault();

    var countryID = jQuery( this ).attr( 'title' ); // <-- !!!

    location.href = location.href.split( '#' )[0] + '#' + countryID;
    location.reload();

} );

or

/* using plain JS */
var countryAnchors = document.querySelectorAll( '.menu a' );
for( var anchor in countryAnchors ) {
    anchor.addEventListener( 'click', function( event ) {
        event.preventDefault();

        var countryID = this.getAttribute( 'title' ); // <-- !!!

        location.href = location.href.split( '#' )[0] + '#' + countryID;
        location.reload();

    }, false );
}
/* todo: cross-browser test for compatibility on querySelectorAll() and addEventListener() */

Upvotes: 2

Tony Dinh
Tony Dinh

Reputation: 6726

It just simple like this:

function cselect(){
    var countryID = $(this).attr("title");
    window.location.hash = countryID
    location.reload();
}

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Pass in this to your inline handler:

function cselect(obj){
    var countryID = $(obj).attr("title");
    console.log(countryID);
}

<a href="#" title="4242" onclick="cselect(this)">United States</a>
<a href="#" title="4243" onclick="cselect(this)">Canada</a>

Demo: http://jsfiddle.net/yDW3T/

Upvotes: 3

Related Questions