JQuery: Mark (select) content text by tag name without id

I want to select content text in certain tags, for example code

by clicking on it (ready to copy).

I foudn solutions when you have an ID but my codemarks have no IDs:

<p>When I click <code>this code</code> I want it to be selected.</p>
<p>The code tags don't have IDs or tag names.</p>
<p>Here some <code>other code</code>.</p>

      

This does not work:

$("code").click(function(){
    $(this).select();
});

      

Seems select()

to be for inputs and text fields only.

Test: http://jsfiddle.net/n6R3t/

+3


source to share


3 answers


Try this jQuery plugin shared by Jason Edelman in this answer :

jQuery.fn.selectText = function(){
    var doc = document
        , element = this[0]
        , range, selection
    ;
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();        
        range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    }
};

      



Then you can use it like this:

$('code').click(function() {
    $(this).selectText();
});

      

+3


source


As you said, the method $.select()

only works for input / textareas. You will need to use a combination of window.getSelection and document.selection (in older browsers).

$("code").click(function(){
    if (document.selection) {
        // older browsers
        var range = document.body.createTextRange();
        range.moveToElementText(this);
        range.select();
    } else if (window.getSelection) {
        // modern browsers
        var range = document.createRange();
        range.selectNode(this);
        window.getSelection().addRange(range);
    }
});

      



See fiddle: http://jsfiddle.net/derekaug/8Ax79/

+1


source


.select()

fires a select event. This is shorthand for javascript .trigger("select")

http://api.jquery.com/select/ , so you need to declare an event handler for your code so that it doesn't do anything, similar to the click handler you already have.

$("code").select(function(){your code for what happens on select});

Add this after your code click

and it should answer.

0


source







All Articles