How to know if there is a link element within the selection

后端 未结 5 1552
心在旅途
心在旅途 2021-01-06 03:46

In Javascript, I\'d like determine whether an element, say an A element, exists inside a given range/textRange. The aim is to determine if the user\'s current

5条回答
  •  借酒劲吻你
    2021-01-06 04:05

    I'm using this code that works with IE / Chrome / FF: (I'm using it to select rows in a table)

    // yourLink is the DOM element you want to check
    var selection = window.getSelection().getRangeAt(0)
    var node = document.createRange()
    node.selectNode(yourLink)
    var s2s = selection.compareBoundaryPoints(Range.START_TO_END, node)
    var s2e = selection.compareBoundaryPoints(Range.START_TO_START, node)
    var e2s = selection.compareBoundaryPoints(Range.END_TO_START, node)
    var e2e = selection.compareBoundaryPoints(Range.END_TO_END, node)
    if ((s2s != s2e) || (e2s != e2e) || (s2s!=e2e))
        console.log("your node is inside selection")
    

提交回复
热议问题