简体   繁体   中英

add class to anchor in jQuery

is it possible to add a class to the anchor in the code below? because i have a conflict with other anchors...

function SelectText(element) {
  var doc = document;
  var text = doc.getElementById(element);    
  if (doc.body.createTextRange) {
    var range = document.body.createTextRange();
    range.moveToElementText(text);
    range.select();
  } else if (window.getSelection) {
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(text);
    selection.removeAllRanges();
    selection.addRange(range);
  }
}


$( document ).ready(function() {
  $('a').click(function() {
    SelectText( $(this).attr("rel") );
  });
})

EDIT: I want to catch all code in a code block and use the rel attribute for it. I use this php line for it:

$output ='<br /><br /><a rel="highlight'.$element_id.'" class="selectable">[Select All]</a>'; // assign unique ID to rel attribute

The div in which the code is has the same unique ID, so i use the rel to catch the code. But somehow it gives me a problem with the other anchors, they do not work correctly anymore. So i thought: if i add a class to the anchor, it might be listening only to the a with that specific class name

Use $(this).addClass() . That is the element being clicked.

$(document).ready(function() {
    $('a').click(function() {
        $(this).addClass('selectable');
    }
}

http://api.jquery.com/addclass/

Or if you are talking about using the click handler only for a tags with the class selectable you can do:

$(document).ready(function() {
    $('a.selectable').click(function() {
        SelectText( $(this).attr("rel") );
    }
}

You'll need to add an ID to the anchor you want to add a class to, then with jquery, you can use .addClass() - http://api.jquery.com/addclass/

IE

$( "#yourAnchorID" ).addClass( "myClass yourClass" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM