javascript - 如何使用 jQuery 包装带有混合 <a> 标签的文本节点?

标签 javascript jquery html

我是 jQuery 的新手。我想做一个 chrome 扩展。但是有些网页有如下HTML,我想对其进行预处理并使其更清晰。

<div>
  Hello 
  <a href="#">World</a>
  !!!!!!
  <br />
  Nice to meet you
  <img src="#">
</div>

我想包装所有由 <br> 分隔的文本节点标记为 p标签,但跳过 a之间的标签,最后删除 <br>标签。 (它只是跳过 a 标签,不应该跳过任何其他标签,文本应该被包装到那一点)。上面的例子应该转换如下:

<div>
  <p>Hello <a href="#">World</a>!!!!!!</p>
  <p>Nice to meet you</p>
  <img src="#">
</div>

如何使用 jQuery 进行上述转换?

我找到了相关答案,但不知道如何跳过 a标签。

$("body br").each(function () {
  $.each([this.previousSibling, this.nextSibling], function() {
    if (this.nodeType === 3) { 
      $(this).wrap('<p></p>');
    }
    // Should skip over a tags
  });

  $(this).remove(); 
});

再次尝试,但失败了(最后要合并的元素出现了两次)。

$("body br").each(function() {
  $.each([this.previousSibling, this.nextSibling], function() {
    if (this.nodeType === 3) {
      $(this).wrap('<p></p>');
    }
    // Should skip over a tags
  });

  $(this).remove();
});

//Wrap all <br> tags with <p>
var to_be_deleted = new Array();
var just_finished = false;

function is_finished() {
  return just_finished;
}

function set_finished(val) {
  just_finished = val;
}

$('body br').each(function() {
  $.each([this.previousSibling, this.nextSibling], function() {
    if (this.nodeType === 3) { // 3 == text
      if ($(this).parent().is("p")) {
        console.log("Parent is p");
      }
      if (this.nextSibling) {

        var curr = this.nextSibling;
        var count = 0; // How many elements merged
        var till_now = $('<p class="merged_block">');
        $(till_now).append($(this).clone());
        while (curr) {
          if (curr.tagName === "A") {
            var a_elem = $(curr).clone();
            $(till_now).append(a_elem);
            to_be_deleted.push(curr);
            count++;

          } else if (curr.nodeType === 3) {
            var n_elem = $(curr).clone();
            $(till_now).append(n_elem);
            to_be_deleted.push(curr);
            count++;

          } else {
            break;
          }

          curr = curr.nextSibling;
        }

        if (count > 0) {
          $(this).before(till_now);
          $(this).remove();
          set_finished(true);
        }

      } else {
        if (is_finished()) {
          $(this).remove();
          set_finished(false);
        } else {
          $(this).wrap('<p></p>'); // Last <br/>
        }

      }
    }
  });

  $(this).remove(); //-- Kill the <br>
});

$.each(to_be_deleted, function(i, e) {
  $(e).remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  Hello <a href="#">World</a> blablah
  <br /> Nice to meet you
  <img src="#">
</div>

最佳答案

这是我解决问题的方法:

$(document).ready(function(){
    var dad = document.getElementById("dad"),
        container = document.getElementById("container"),
        elem = container.childNodes,
        parent = document.createElement("div"),
        newElem = document.createElement("p");

    while($(container).html() !== "") {
        if (elem[0].nodeName == "#text") {
            newElem.appendChild(elem[0]);
            elem.data = "";
        } else if (elem[0].nodeName == "BR") {
            parent.appendChild(newElem);
            newElem = document.createElement("p");
            container.removeChild(elem[0]);
        } else {
            newElem.appendChild(elem[0]);
            container.removeChild(elem[0]);
        }
    }
    parent.appendChild(newElem);
    newElem = document.createElement("p");

    dad.removeChild(container);
    parent.id = "container";
    dad.appendChild(parent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body id="dad">
  <div class="container" id="container">
    Hello 
    <a href="#">World</a>
    !!!!!!
    <br />
    Nice to meet you
    <img src="#">
  </div>
</body>

关于javascript - 如何使用 jQuery 包装带有混合 <a> 标签的文本节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27177095/

相关文章:

javascript - 在 ExpressJS 中使用带有数组的 JSON

javascript - 有没有办法使用 JavaScript 将 PNG 的白色背景转换为透明背景?

html - 双边框样式不适用于 outlook

javascript - 试图在屏幕上找到 javascript 元素的位置....在 webkit 浏览器上无法正常工作

javascript - 内联事件处理程序中的神秘变量 "URL"

javascript - 如何使用 javascript 或 jquery 验证自定义属性中是否存在某个值?

javascript - jQuery 函数扩展的范围问题

javascript - React search(filter)函数,添加参数进行搜索

javascript - 为什么这个对象循环不起作用?