mix
mix

Reputation: 7151

Find HTML Element that has Specific Attribute Using jQuery

How can I target an HTML element that has a specific attribute, but when that attribute has no value (well, whether it has a value or not). I've found others asking similar questions about elements with attribute values but not based on existence of the attribute itself.

For example, with this HTML:

<div id="id1">
  <div class="c1"></div>
  <div class="c2" an-attribute ></div>
  <div class="c3"></div>
</div>

How might I go about finding the div within #id1 that has the attribute an-attribute? I can't count on it being in a particular location related to the other divs but can count on it being in #id1.

Upvotes: 1

Views: 230

Answers (7)

Naga Sai A
Naga Sai A

Reputation: 10975

$("div").children().attr("an-attribute");

Upvotes: 0

Dharmesh Kumar Laxkar
Dharmesh Kumar Laxkar

Reputation: 411

var element=$('#id1').find('div[an-attribute]');

Upvotes: 0

Mani
Mani

Reputation: 2655

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
							
<script>
$(document).ready(function(){

	$('[an-attribute]').css("color","red")

});
</script>

<div id="id1">
  <div class="c1">dsadsa1</div>
  <div class="c2" an-attribute >dsdsads2</div>
  <div class="c3">dsadsad3</div>
</div>

Upvotes: 0

Toney
Toney

Reputation: 66

alert($('[an-attribute]').attr('class'));  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <body>
    <div an-attribute class="111111111"></div>
  </body>
</html>

Upvotes: 0

Prakash Bhandari
Prakash Bhandari

Reputation: 567

Here is sample code. i have used to identify the attribute.

HTML Code

<div id="id1">
        <div class="c1"></div>
        <div class="c2" id="testr">dd</div>
        <div class="c3"></div>
    </div>

JavaScript Code

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

<script>
    $('.c2').on('click',function(){
        var id =$(this).attr('id')
        alert(id);
    })
</script>

Upvotes: 0

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

You can simply use an attribute selector:

$('div[an-attribute]') // or $('[an-attribute]')

Upvotes: 3

phreakv6
phreakv6

Reputation: 2165

Try this.

$('#id1 div[an-attribute]');

Upvotes: 5

Related Questions