简体   繁体   中英

Get all DOM block elements for selected texts

When selecting texts in HTML documents, one can start from within one DOM element to another element, possibly passing over several other elements on the way. Using DOM API, it is possible to get the range of the selection, the selected texts, and even the parent element of all those selected DOM elements (using commonAncestorContainer or parentElement() based on the used browser). However, there is no way I am aware of that can list all those containing elements of the selected texts other than getting the single parent element that contains them all. Using the parent and traversing the children nodes won't do it, as there might be other siblings which are not selected inside this parent.

So, is there is a way that I can get all these elements that contains the selected texts. I am mainly interested in getting the block elements (p, h1, h2, h3, ...etc) but I believe if there is a way to get all the elements, then I can go through them and filter them to get what I want. I welcome any ideas and suggestions.

Thank you.

Key is window.getSelection().getRangeAt(0) https://developer.mozilla.org/en/DOM/range

Here's some sample code that you can play with to do what you want. Mentioning what you really want this for in question will help people provide better answers.

var selection = window.getSelection();
var range = selection.getRangeAt(0);
var allWithinRangeParent = range.commonAncestorContainer.getElementsByTagName("*");

var allSelected = [];
for (var i=0, el; el = allWithinRangeParent[i]; i++) {
  // The second parameter says to include the element 
  // even if it's not fully selected
  if (selection.containsNode(el, true) ) {
    allSelected.push(el);
  }
}


console.log('All selected =', allSelected);

This is not the most efficient way, you could traverse the DOM yourself using the Range's startContainer/endContainer, along with nextSibling/previousSibling and childNodes.

You can use my Rangy library to do this. It provides an implementation of DOM Range and Selection objects for all browsers, including IE, and has extra Range methods. One of these is getNodes() :

function isBlockElement(el) {
    // You may want to add a more complete list of block level element
    // names on the next line
    return /h[1-6]|div|p/i.test(el.tagName);
}

var sel = rangy.getSelection();
if (sel.rangeCount) {
    var range = sel.getRangeAt(0);
    var blockElements = range.getNodes([1], isBlockElement);
    console.log(blockElements);
}

It sounds like you could use Traversing from the jQuery API .

Possibly .contents()

Hope that helps!

Here is a es6 approach based on @Juan Mendes response:

const selection = window.getSelection();
const range = selection.getRangeAt(0);
const elementsFromAncestorSelections = range.commonAncestorContainer.getElementsByTagName("*");

const allSelectedElements = Array.from(elementsFromAncestorSelections).reduce(
  (elements, element) =>
    selection.containsNode(element, true)
      ? [...elements, element]
      : elements,
  [],
);

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