Aariba
Aariba

Reputation: 1194

How to replace text to make class of a div

Trying to replace text to class of a div. Means find text from .label (text1 or any text), then replace it as class class="text1" to parent list <li> item like <li class="text1">. Example given below

HTML:
This is main output html code.

<div id="main-id">
<ul>

<li> <!--List 1-->
<span class="meta">
<div class="label">
<a href="http://lorem.com">text1</a>
</div>
</span>
</li>

<li> <!--List 2-->
<span class="meta">
<div class="label">
<a href="http://lorem.com">text2</a>
</div>
</span>
</li>

</ul>
</div>

By Jquery/JS output html like this: (I want this)

<div id="main-id">
<ul>

<li class="text1"> <!--Add class to List 1-->

<span class="meta">
<div class="label">
<a href="http://lorem.com">text1</a> <!--Get class name from here-->
</div>
</span>
</li>

<li class="text2"> <!--Add class List 2-->

<span class="meta">
<div class="label">
<a href="http://lorem.com">text2</a> <!--Get class name from here-->
</div>
</span>
</li>

</ul>
</div>

I am using this Replace text script, but i unable to do that. Any suggestion for other way to do this?
Thanks in advance.

Upvotes: 0

Views: 107

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115222

You can use addClass() to add class

$('.label a').each(function() {
   var $this=$(this);      
   $this.closest('li').addClass($this.text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main-id">
  <ul>

    <li>
      <!--List 1-->
      <span class="meta">
<div class="label">
<a href="http://lorem.com">text1</a>
</div>
</span>
    </li>

    <li>
      <!--List 2-->
      <span class="meta">
<div class="label">
<a href="http://lorem.com">text2</a>
</div>
</span>
    </li>

  </ul>
</div>

Upvotes: 3

Vonfry
Vonfry

Reputation: 365

use for each $('li)

addClass() can add class. Or use attr() method.

Upvotes: 1

Data
Data

Reputation: 1357

jsfiddle

function replace(){

    var arr = [];

    $('div .label').each( function(){ // search for divs with a label
        arr.push( $(this).text() );
    });

    // add class to each <li>
    $('li').each( function(index, element){
        $(this).addClass(arr[index]);
    });
}

replace();

Upvotes: 1

Related Questions