joe
joe

Reputation: 219

Removing if element has an specific data value jquery

EXPECTED

When clicking on button I want it to alert the data-type value

HTML

<ul id="threads">
 <li data-href='q' data-type='m'>abc <button>Click</button></li>
 <li data-href='q' data-type='t'>mnp <button>Click</button></li>
 <li data-href='r' data-type='t'>rst <button>Click</button></li>
 </ul>

JQUERY

   $(document).on("click","button",function(){


  var  element = $(document).find("div").find("[data-href='q']");

   if(element....has data-type='m'?){alert("this is m type"); }
  if(element....has data-type='t'?){alert("this is t type"); }



    })

This is taking me more time than expected, does anyone knows the way to go?

Upvotes: 0

Views: 41

Answers (3)

Akilesh Kumar R
Akilesh Kumar R

Reputation: 398

$(document).ready(function(){
	$("#threads button").click(function(){
		var datatype = $(this).parent().attr("data-type");
		if(datatype == 'm'){
			alert(datatype);
		}else{
			alert(datatype);
		}
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<ul id="threads">
 <li data-href='q' data-type='m'>abc <button>Click</button></li>
 <li data-href='q' data-type='t'>mnp <button>Click</button></li>
 <li data-href='r' data-type='t'>rst <button>Click</button></li>
 </ul>

I think this method will helps you lot

Upvotes: 1

Taplar
Taplar

Reputation: 24965

$('#threads').find('li').filter("[data-href='q'][data-type='m']").remove();

Find the parent by id, find the nested lis, then filter those that have both a q and an m, and remove them/it.

As to why I have the selector broken up into three steps, you can refer to http://learn.jquery.com/performance/optimize-selectors/ for more reading.

Here is an alternate version using a conditional.

var $threadItems = $('#threads').find('li');

$threadItems.each(function(index, item){
    var $item = $(item);

    if ($item.data('href') === 'q') {
        if ($item.data('type') === 'm') {
            $item.remove();
        }
    }
});

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68687

$("#threads li[data-href='q'][data-type='m']").remove();

Upvotes: 1

Related Questions