سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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);
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top