Wrap a piece of text in a new item tag

I have text in a tag <span>. I want to wrap part of this text in another element tag with an identifier that is not in the underlying HTML. Since I cannot change the basic HTML, I am forced to use JavaScript/JQueryfor this.

I have this HTML code:

<span id="my_span">John<input type="hidden" name="firstname" value="John" id="my_input1">
<br>Smith<input type="hidden" name="lastname" value="Smith" id="my_input2">
</span>

I want to add a tag <a>with an identifier to texts within this range. The text I want to wrap is dynamic, so I cannot use the value inside as such to search for and target it. The HMTL code should look like the following after applying the code JavaScript/JQuery:

<span id="my_span"><a id="added_a_tag1">John</a><input type="hidden" name="firstname" value="John" id="my_input1">
<br>
<a id="added_a_tag2">Smith</a><input type="hidden" name="lastname" value="Smith" id="my_input2">
</span>

It sounds simple, but I could not reach it.

I will need to target those newly added identifiers for something even later.

I appreciate your answers.

+4
3

jquery .contents(), <span>. (nodeType of 3). <a>, . ( , <a> ).

. .

$(document).ready(function() {
  var count = 0;
  $('#my_span').contents()
    .filter(function() {
      return this.nodeType === 3
    })
    .each(function() {
      if ($.trim($(this).text()).length > 0) {
        $(this).wrap('<a href id="added_a_tag_' + (++count) + '"></a>');
      }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="my_span">
  John<input type="hidden" name="firstname" value="John" id="my_input1">
  <br>
  Smith<input type="hidden" name="lastname" value="Smith" id="my_input2">
</span>
Hide result
+3

<span> .

<span id="name_1">John</span>

var currentText = $("#name_1").innerHTML;
 $("#name_1").replaceWith('<a id="dynamic_1">' + currentText + '</a>');

id , .

0

.map(), Array.prototype.forEach(), .html(), .replace()

$("#my_span").map(function() {
  // split new line character of `#my_span` `.textContent`
  var txt = this.textContent.split("\n").filter(Boolean);
  // iterate each `txt`
  txt.forEach(function(val, index) {
    $(this).html(function(_, html) {
      // replace `val` with `a` element
      return html.replace(val, $("<a />", {
        "text": txt[index],
        "id": "added_a_tag" + (index + 1),
        "href": "#"
      })[0].outerHTML)
    })
  }.bind(this))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="my_span">John<input type="hidden" name="firstname" value="John" id="my_input1">
<br>Smith<input type="hidden" name="lastname" value="Smith" id="my_input2">
</span>
Hide result
0

Source: https://habr.com/ru/post/1613386/


All Articles