0

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.

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
  • 1
    It's not a duplicate. I mean clearly OP can select by attribute using jQuery, but they should never do this in angular. Instead this should be done with a directive. – dfsq Jul 12 '16 at 09:58
  • 1
    There is no such thing as a 'text element,' can you please give an example of the HTML you're trying to describe? And what attribute are you looking for? What do you want to do on the 'click' event? – David Thomas Jul 12 '16 at 09:59
  • It is marked jQuery. Duplicate of this then? http://stackoverflow.com/questions/11913841/accessing-attributes-from-an-angularjs-directive - I closed it and then I saw the "text with attribute" which does not make sense anyway. OP needs to show examples of html with or without the attribute he meant – mplungjan Jul 12 '16 at 10:00

3 Answers3

2

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])'
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
2

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')
      })
    }
  }
})
dfsq
  • 191,768
  • 25
  • 236
  • 258
0

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>
Mohammad
  • 21,175
  • 15
  • 55
  • 84