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:
Solution 1:
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>
Solution 2:
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() */
Solution 3:
It just simple like this:
function cselect(){
var countryID = $(this).attr("title");
window.location.hash = countryID
location.reload();
}
Post a Comment for "How To Get Title Attribute From Link Within A Class With Javascript"