Belal Mostafa Amin
Belal Mostafa Amin

Reputation: 80

Restructuring html elements

I have the following HTML element structure:

<span class="parent">
    <span class="keyword">belal</span>
    <span class="string"> "Belal Mostafa"</span>
</span>

now I want to dynamically select the .parent class and restructure its children it to look like:

<span class="parent">
    <span class="keyword">belal</span>
    <span class="string"> "Belal </span>
    <span class="string"> Mostafa"</span>
</span>

I was thinking of the following but still can't get it done:

Upvotes: 0

Views: 176

Answers (2)

Jyothi Babu Araja
Jyothi Babu Araja

Reputation: 10292

You can do this with jQuery append

var text  = $(".string").text().trim(); //getting text of string element
$(".string").remove(); //removing existing
text.split(" ").forEach(function(item){ //splitting it to append span elements
  $(".parent").append("<span class='string'>" + item + "</span>"); //appending to parent element
});
.string{
  border: 1px solid blue; /*just for view, remove it later*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="parent">
    <span class="keyword">belal</span>
    <span class="string"> "Belal Mostafa"</span>
</span>

Upvotes: 1

Alexis
Alexis

Reputation: 5831

You can loop on each .parent, after that loop on each string and split all white space and append the result to the parent.

Example

$(".parent .string").each(function(){
  if($(this).text().trim().indexOf(" ") != -1)
  {
    var parent = $(this).parents(".parent");
    $.each($(this).text().trim().split(" "),function(index,value){
      parent.append("<span class='string'>"+value+"</span>");
    });
    $(this).remove();
  }
});
.string{
  border:solid 1px #888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="parent">
    <span class="keyword">belal</span>
    <span class="string"> "Belal Mostafa Test"</span>
</span>

Upvotes: 2

Related Questions