Code Guru
Code Guru

Reputation: 15598

How to get element with tag name having specific attribute in jquery or angularjs

I have a div having many tags inside. I want to bind the click event on all text elements that have x attribute.

I have tried

$('#attendacneLineChart').find('text')

but this returns all the text elements. But I need only those text element that has x attribute.

Upvotes: 0

Views: 775

Answers (3)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

use

$('#attendacneLineChart').find('text[X]')

if you want to ignore some elements with specific attr you can use :not

$('#attendacneLineChart').find('text[X]:not([y])') // for more use 'text[X]:not([y]):not([z])'

Upvotes: 2

Mohammad
Mohammad

Reputation: 21489

You can use jquery [attribute='value'] selector to finding element has specific attribute.

$("div > p[myAttr]").click(function(){
    console.log($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <p>Text1</p>
    <p myAttr="1">Text2</p>
    <p>Text3</p>
    <p myAttr>Text4</p>
</div>

Upvotes: 0

dfsq
dfsq

Reputation: 193291

I want to bind the click event on all text elements that have x attribute.

Create directive for this:

.directive('x', function() {
  return {
    link: function(scope, element) {
      element.click(function() {
        console.log('clicked')
      })
    }
  }
})

Upvotes: 2

Related Questions