Добавление якоря после текста HTML - PullRequest
0 голосов
/ 01 октября 2018

Я работаю над расширением Chrome для развлечения, где я ищу на странице какой-нибудь текст из массива констант.Чтобы добиться этого, я получаю все элементы на странице с текстом, затем циклически перебираю свой массив констант и массив узлов (что меня немного не устраивает с точки зрения производительности ...).Как только я найду соответствие, я хочу добавить привязку, которая выполняет действие после текста.

В качестве примера, где "target" - это слово, которое я ищу:

<p>You should really find the target better!</p>

Я бы хотел, чтобы все закончилось так:

<p>You should really find the target<a attr-name="target"> +</a> better!</p>

Я попробовал несколько методов, в которых я попытался insertAdjacentElement, хотя в этом контексте это не будет работать, так как элементабзац, а не целевой текст, поэтому он просто добавляет якорь в конец абзаца.

Я также попытался просто вставить его с помощью innerHTML, хотя это кажется немного странным, особенно если другие расширенияделать манипуляции с DOM.

Есть мысли?

Ответы [ 3 ]

0 голосов
/ 01 октября 2018

function walkText(node) {
  if (node.nodeType == 3) {
    node.data = node.data.replace(/target/g, 'target<a href="#" attr-name="target"> +</a>');
  }
  if (node.nodeType == 1 && node.nodeName != "SCRIPT") {
    for (var i = 0; i < node.childNodes.length; i++) {
      walkText(node.childNodes[i]);
    }
  }
}
walkText(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
</body>

Для этого можно использовать функцию replace().Вот пример.

var str = "<p>You should really find the target better!</p>";
var res = str.replace("target", 'target<a href="#" attr-name="target"> +</a>');

Это должно работать для вас

0 голосов
/ 01 октября 2018

Надеюсь, это результат, который вы ищете?

function walkText() {
  document.body.innerHTML = document.body.innerHTML.replace(/target/g, 'target <a attr-name="target"> +</a>');
}
walkText(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
<div class="test"><p>You should really find the target better!</p></div>
</body>
enter image description here
0 голосов
/ 01 октября 2018

В случае привязки вам нужно добавить атрибут href must, чтобы он действовал как ссылка

<p>You should really find the target<a href="#" attr-name="target"> +</a> better!</p>

Надеюсь, это то, что вы ищете ..

Спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...