user1642545 user1642545 - 7 months ago 21
HTML Question

How to use an element's attribute value to target another element with an identical attribute value in jQuery?

I have a menu of a list of article names

list-A
, and a corresponding list of articles content,
list-B
. Each list A and list B item pair share an identical value in their class eg.
class="orderCntrl-6062347"
.

I want to be able to select an item from list A to bring the corresponding article from list B to the top of list B.

I know how to re-order the lists by using the following to bring a selected item to the top of a list:

$("li.orderIt").click(function() {
$(this).parent().prepend($(this));
});


This is what my code currently looks like:

<!-- List A selecting an item here should bring selected item and paired item in list B to the top of each of their lists -->
<ul class="list-A">
<li class="orderIt orderCntrl-6062347"><a>Item 1</a></li>
<li class="orderIt orderCntrl-6062348"><a>Item 2</a></li>
<li class="orderIt orderCntrl-6062349"><a>Item 3<a></li>
</ul>
<ul class="list-B">
<li class="orderCntrl-6062347"><h2 class="newsTitle">Item One</h2></li>
<li class="orderCntrl-6062348"><h2 class="newsTitle">Item Two</h2></li>
<li class="orderCntrl-6062349"><h2 class="newsTitle">Item Three</h2></li>
</ul>

<!-- Script to bring accompanying article to top of list on selecting side menu - currently only bring elements in List A to the top of their lists -->
<script>
$("li.orderIt").click(function() {
$(this).parent().prepend($(this));
});
</script>


Here's a link to how things will look, the green side menu is
list-A
(it may be above the page title on screens under 1300px).

How do I adjust the script to bring the corresponding list B item to the top as well?

Answer

Is this kind of what you are looking for?

https://jsfiddle.net/stevenkaspar/61oL0Lfm/

<ul class="list-A">                 
  <li class="orderCntrl-6062347" data-news-target='#news1'><h2 class="newsTitle">Item One</h2></li>
  ...

<!-- List B -->
<ul class="list-B">                 
  <li id='news1'>NEWS One</li>   

<script>           
  $("[data-news-target]").click(function() {      

    $(this).parent().prepend($(this));    

    var target_element = $( $(this).data('newsTarget') );
    target_element.parent().prepend( target_element );              
  });
</script> 

You can use data-news-target to say what element it will move