0

Following is my code. I'm trying to select an element based on tow attributes , one a class using .class selector. and other using a data attribute [data-depth='2'] .

jQuery(document).on('click', ".node [data-depth='2']", function() {
  alert("clicked");
})
.node {
  height: 30px;
  width: 150px;
  padding: 5px;
  background: #EF4836;
  margin: 10px;
  cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="node" data-depth="2">
  Click me
</div>

<div class="node" data-depth="3">
  Do not Click me
</div>

But the element is not getting selected. What am i doing wrong ?

3 Answers 3

4

Remove the space between .node and [data-depth='2']. Space means descendant elements of .node has attribute data-depth="2".

jQuery(document).on('click', ".node[data-depth='2']", function() {
    alert("clicked");
})
.node {
  height: 30px;
  width: 150px;
  padding: 5px;
  background: #EF4836;
  margin: 10px;
  cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="node" data-depth="2">
  Click me
</div>

<div class="node" data-depth="3">
  Do not Click me
</div>

Sign up to request clarification or add additional context in comments.

Comments

2

jQuery(document).on('click', "[data-depth='2'].node", function() {
  alert("clicked");
})
.node {
  height: 30px;
  width: 150px;
  padding: 5px;
  background: #EF4836;
  margin: 10px;
  cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="node" data-depth="2">
  Click me
</div>

<div class="node" data-depth="3">
  Do not Click me
</div>

It should have no space between them. If there is space it will be looking for the child of the class nodethat has [data-depth='2']

Comments

0

Another Method

This will have more of practical use:

HTML

Click me

 <div class="node" data-depth="3">
    Do not Click me
 </div>

JAVASCRIPT

$(document).on('click', ".node", function() {
_this = $(this);
_depth = _this.data("depth");

  switch(_depth) {
   case 2: alert('clicked '+ 2);break;
   case 3: alert('clicked '+ 3);break;
   default : alert('clicked other')
  }
})

Comments

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.