3

I am receiving HTML that is in various formats and I'm trying to standardize the code using jQuery. In some cases I receive it using breaks <br> to separate lines. I need these to be <div> (or <p>) tags instead. For instance the following code:

a<br>b<br>c

needs to be converted into

<div>a</div><div>b</div><div>c</div>

This is a simple case as the contents in a could be surrounded by all kinds of <font>, <span> and other formatting options, all of which need to be retained.

Here was my first attempt. It finds all the <br> tags in the entire document then accesses the parent's contents to get all the HTML around the <br>. If the contents length is 1 then <br> is the only element in there (meaning a blank line) so skip on to the next one. Otherwise look at each element, surround it with <div> (or <p>) and remove the <br> as it isn't needed any more. Variable wrapper is either "<div />" or "<p />" depending on the browser.

$("br").each(function() {
  // Find all the br tags' parent nodes
  var elements = $(this).parent().contents();
  if (elements.length > 1) {
    // If there is one element than it is br so skip on.
    elements.each(function() {
      // Loop through each child element of the parent 
      var nodeName = this.nodeName.toLowerCase();
      if (nodeName !== 'div' && nodeName !== 'p') {
      // Make sure each child that is not <br> is wrapped. Remove <br> tags.
        if (nodeName == 'br') {
          $(this).remove();
        } else {
          $(this).wrap(wrapper);
        }
      }
    });
  }
});

This doesn't work, though, as it adds <div> (or <p>) tags around every sub-element so something like <font>a</font>bc<br>de<b>f</b> ends up like

<div><font>a</font></div>
<div>bc</div>
<div>de</div>
<div><b>f</b></div>

when it really needs to be

<div><font>a</font>bc</div>
<div>de<b>f</b></div>

(I broke it up to be easier to read.)

If I was doing this in a text parser, I'd find the contents just like I did above for variable elements, add a <div> at the beginning and a </div> at the end, then replace each <br> with </div><div> (except when it is already <div><br></div>, at which point I'd skip it). I have no idea how to do this in jQuery/Javascript. though, especially regarding the replace <br> with </div><div> portion. (The first part is elements.wrap(wrapper).)

Any help on this approach or an alternative approach would be appreciated.

--- UPDATE ---

@Ian supplied must of the code that worked. I expanded on it just a little and thought I'd include it here. I have tested it in FF, Safari, Chrome and IE 9+.

$("br").each(function(idx, el) {
    var $el = $(el),
        $parent = $el.parent(),
        $contents = $parent.contents(),
        $cur, $set, i;

    $set = $();
        if ($contents.length > 1) {
        for (i = 0; i < $contents.length; i++) {
            $cur = $contents.eq(i);

            if ($cur.is("br")) {
                $set.wrapAll(wrapper);
                $cur.remove();
                $set = $();
            } else {
                $set = $set.add($cur);
            }
        }
        $set.wrapAll(wrapper);
    }
});
4

6 に答える 6

3

説明した正確なテキスト置換方法を実行できます。

function changeBrToDiv(node) {
  var html = $(node).html();
  html = "<div>" + html.split("<br>").join("</div><div>") + "</div>";
  node.html(html);
}

これは jsFiddle で実際に確認できます。

于 2013-08-28T17:32:43.167 に答える
1

br私には、トラバースが完了するまでタグを DOMに残しておきたいと思うかもしれません。2 番目の例の場合、参照ポイントとしてタグdivを残していない限り、開始タグで到達する高さがわかりません。親要素を取得し、開始または abrが見つかるまで DOM を検索し、そこに開始タグを叩きます。すすいで繰り返す<body><br>

于 2013-08-28T17:32:27.547 に答える
0

これがあなたの問題かもしれないと思います:

var elements = $(this).parent().contents();

する必要があります

var elements = $(this).parent().children();

コンテンツはテキスト要素もノードとして返すため、子は実際の dom 要素のみを返すため

于 2013-08-28T17:31:55.467 に答える
0

POJS でこのようなことを試すことができます。マークアップをテキストとして扱うのではなく、DOM を操作します。正確な要件に合わせて、わずかに変更する必要がある場合があります。

HTML

<div>one
    <br>two</div>
<br>
<div>
    <br>
</div>
<div>
    <div>three
        <br><font>a</font>bc
        <br>de<b>f</b>

    </div>
</div>
<span>a</span>

<br>b<span>c</span>d
<br>e<span>f</span>g

Javascript

function prepend(referenceNode, newNode) {
    if (referenceNode.firstChild) {
        referenceNode.insertBefore(newNode, referenceNode.firstChild);
    } else {
        referenceNode.appendChild(newNode);
    }
}

var brs = document.getElementsByTagName("br"),
    docFragment = document.createDocumentFragment(),
    index1,
    index2,
    parent,
    siblings,
    sibling,
    br;

for (index1 = brs.length - 1; index1 >= 0; index1 -= 1) {
    div = document.createElement("div");
    br = brs[index1];
    parent = br.parentNode;
    siblings = parent.childNodes;
    for (index2 = siblings.length - 1; index2 >= 0; index2 -= 1) {
        sibling = siblings[index2];
        if (sibling === br) {
            break;
        }

        prepend(div, sibling);
    }

    prepend(docFragment, div);
    br.parentNode.removeChild(br);
    if (!brs.length && siblings.length) {
        div = document.createElement("div");
        for (index2 = siblings.length - 1; index2 >= 0; index2 -= 1) {
            prepend(div, siblings[index2]);
        }

        prepend(docFragment, div);
    }

    if (docFragment.childNodes.length && !siblings.length) {
        parent.appendChild(docFragment);
    }
}

の上jsfiddle

于 2013-08-28T20:26:36.793 に答える