pourmesomecode
pourmesomecode

Reputation: 4358

Target element by attr then append class jQuery

I have a li tag that looks like :

<li class="item maybe" data-selected="1"></li>
<li class="item confused" data-selected="2"></li>
<li class="item why" data-selected="3"></li>

I then have three other elements that look like :

<li class="display"></li>
<li class="display"></li>
<li class="display"></li>

I'm trying to on select of one of the elements append the class to my 2nd list of elements.

So if I selected the li tag with data-selector="1" then my first li tag in my display list will have the class maybe added.

This is what i've tried so far, but i'm getting undefined when I console log my var out :

if ($('.item').attr('data-selected') == 1) {
  var itemClassAdd = $('.item').find("[data-selected='1']").attr('class');
  console.log(itemClassAdd);

  $(".display").addClass(itemClassAdd);
}

Thanks!

Upvotes: 0

Views: 88

Answers (2)

erikscandola
erikscandola

Reputation: 2936

I perform action in a click event for convenience:

$("li.item").click(function(){
    var index = $(this).data("selected");

    $("li.display").eq(index - 1).addClass($(this).attr("class"));
});

If you don't need class item:

$("li.item").click(function(){
    var index = $(this).data("selected");
    var c = $(this).attr("class").replace("item ", "");        

    $("li.display").eq(index - 1).addClass(c);
});

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074949

The class and the attribute are on the same element, so you use a compound selector, not find:

var itemClassAdd = $('.item[data-selected="1"]').attr('class');

But note that

if ($('.item').attr('data-selected') == 1) {

will only branch of the first element matching .item has data-selected="1", which may or may not be what you want.

Live Example:

if ($('.item').attr('data-selected') == 1) {
    var itemClassAdd = $('.item[data-selected="1"]').attr('class');
    $(".display").addClass(itemClassAdd);
}
.maybe {
  color: green;
}
<ul>
  <li class="item maybe" data-selected="1">maybe</li>
  <li class="item confused" data-selected="2">confused</li>
  <li class="item why" data-selected="3">why</li>
</ul>
<ul>
  <li class="display">d1</li>
  <li class="display">d2</li>
  <li class="display">d3</li>
</ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 0

Related Questions