开发者

Need get all A tags in selection in editable iframe and add them attribute "class"

开发者 https://www.devze.com 2023-04-11 04:41 出处:网络
I have an editable <iframe> with the some HTML code in it. I need get all <a> tags in my range. I tried this code but it doesn\'t work:

I have an editable <iframe> with the some HTML code in it. I need get all <a> tags in my range. I tried this code but it doesn't work:

var select = document.getElementById(iframe_id).contentWindow.getSelection();
var range = select.getRangeAt(0);
//HERE I WANT TO FIND ALL TAGS IN THIS RANGE AND IF IT "A"开发者_运维知识库 - ADD NEW ATTRIBUTE "CLASS". SOMETHING LIKE THIS       
var parent = rng.commonAncestorContainer;

for(var i=0; i<parent.childNodes.length; i++)
{
    if(parent.childNodes[i].tagName.toLowerCase() == "a")
        parent.childNodes[i].setAttribute("class", "href_class");
}


You can use getElementsByTagName() to get all <a> tags of the range container and then check for each of them whether it actually belongs to the range using range.compareBoundaryPoints() (only parts of the container might be selected). Something like this:

var links = rng.commonAncestorContainer.getElementsByTagName("a");
for (var i = 0; i < links.length; i++)
{
  var linkRange = document.createRange();
  linkRange.selectNode(links[i]);
  if (rng.compareBoundaryPoints(Range.START_TO_START, linkRange) <= 0 && rng.compareBoundaryPoints(Range.END_TO_END, linkRange) >= 0)
  {
    links[i].className = "href_class";
  }
}


This should get you started in the right direction. This code does not do any null reference checks on the iframe, selection, range or list.

function addAnchorClass(targetFrameId) {

        var targetIframe = document.getElementById(targetFrameId).contentWindow;
        var selection = targetIframe.getSelection();
        var range = selection.getRangeAt(0);
        var alist = range.commonAncestorContainer.getElementsByTagName("a");

        for (var i=0, item; item = alist[i]; i++) {
          if (selection.containsNode(item, true) ) {
            item.className += "PUT YOUR CSS CLASS NAME HERE";
          }
        }
      }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号