Pregunta

I want add class for a child element like in example:

<ul>
    <li class="menu-item">
        <a href="#" title="forum">
            <i class="fa"></i>
            Forum
        </a>
    </li>
</ul>

and js:

$(document).ready(function() {

var title = $(".menu-item a").attr('title');

$(".menu-item a i").addClass(
    function( title ) {
      return "fa-" + title;
    });
});

I don't know how repair this JavaScript.

¿Fue útil?

Solución

I think you are looking for something more like this :

$(".menu-item a").each(function(){
    var title = $(this).attr('title');

    $(this).find("i").addClass("fa-" + title);
});

This will loop through each a and get its own title. It will then add the class to his descendant.

Otros consejos

Try something like this:

$(document).ready(function() {
var title = $(".menu-item a").attr('title');
$(".menu-item a i").addClass("fa-"+title);
});

Working fiddle: http://jsfiddle.net/robertrozas/CTt38/

this will go through each i in .menu-item then add the title attribute of the parent to the class...

$('.menu-item i').addClass(function () {
  return 'fa-' + this.parentNode.title;
});

http://jsbin.com/peyofira/2/edit?html,js,output

this works:

$(document).ready(function() {
var title = "fa-" + $(".menu-item a").attr('title');
$(".menu-item i").addClass(title);
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top