Reputation: 7151
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
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
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
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
Reputation: 21575
You can simply use an attribute selector:
$('div[an-attribute]') // or $('[an-attribute]')
Upvotes: 3