0

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.

1
  • 1
    Are you trying to add a class to the <i> tag, or replace all the classes? Commented May 12, 2014 at 18:26

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

0

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

Comments

0

this works:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.