javascript - Wrap part of text into new element tag -


i have text <span> tag. want wrap part of text element tag id not in base html code. since cannot modify base html code, i'm forced use javascript/jquery so.

i have 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 add <a> tag id texts within span. text want wrap dynamic cannot use value inside such search , target it. hmtl code should shown below after javascript/jquery code applied:

<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> 

sounds simple haven't been able achieve it.

i need target newly added ids else later on.

i appreciate replies.

use jquery's .contents() contents of <span>. filter text nodes (nodetype of 3). loop through each, , wrap <a> tag if not empty. (if don't perform trim , empty check, you'll end <a> tags newline characters inside span).

see working example below.

$(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>


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -