Frage

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");
}
War es hilfreich?

Lösung

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";
  }
}

Andere Tipps

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";
          }
        }
      }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top