简体   繁体   中英

Select some text in html page with JS

I would like to select text automatically (I mean something with the Ranges) in some div to in order to unit test my script in JS.

My problem is that I want to be able to select text in different ways here are some examples of selection (selection represented by [ for start and ] for end)

<div>[ here I select all the text in the div ]</div

<div>This is just a <b>piece [ of</b> selection]</div>

<div><ul><li>Also with [list</li><li>And why not select many items ?</li></ul><p>With a p ?] but not the complete p !</p>

I want to do that because the user can do that and so I should test every cases of use. (If I don't, the unit test is quite useless...)

Do you have an idea about how to select what I want ? (if possible...)

I found this on the web.

This a function that when called on a particular HTML element will auto-select all of its inner text. The function works on elements such as INPUT (text), TEXTAREA, DIV, SPAN, TD, and PRE. Cross browser compatible.

var autoSelect = function(event) {
  var event = event || window.event, 
      elem = event.target || event.srcElement, 
      tag = (elem.tagName || "").toLowerCase(), 
      sel, range;

  if (tag === "textarea" || tag === "input") {
    try {
      elem.select();
    } catch(e) {
      // May be disabled or not selectable
    }
  } else if (window.getSelection) { // Not IE
    sel = window.getSelection();
    range = document.createRange();
    range.selectNodeContents(elem);
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (document.selection) { // IE
    document.selection.empty();
    range = document.body.createTextRange();
    range.moveToElementText(elem);
    range.select();
  }
};

To attach this function to an element:

document.getElementById("foobar").onclick = autoSelect;

You can do it using a regex:

var divStr = document.getElementById('yourDiv').innerHTML;
var matchs = /\[(.*?)\]/.exec(divStr);
console.log(matchs[1]);

We get the inner html string, then parses everything is between [ ], and finnaly get the grouped content.

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