1

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.

1
  • Something like: $('#id1 *[an-attribute]'); Commented Jun 8, 2016 at 4:56

7 Answers 7

5

Try this.

$('#id1 div[an-attribute]');
Sign up to request clarification or add additional context in comments.

Comments

3

You can simply use an attribute selector:

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

Comments

0

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>

Comments

0

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>

Comments

0

<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>

Comments

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

1 Comment

Please consider adding some explanations
0
$("div").children().attr("an-attribute");

1 Comment

This doesn't actually answer the question. This code will retrieve the value of an attribute if you've already found an element. The OP was asking how to find an element based on whether an element has an attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.