skip to Main Content

is it possible with jquery to use DOM to find an a link inside a div, such as

<div id="something">
<a href="somewhere" title="something">
<img>
</a>
</div>

and append a datum to the link – in my case a google events tag:

onClick="_gaq.push(['_trackEvent', ' PDF Downloads', ‘Click', 'SEO For Beginners');"

dynamically to the a link so that the end result would be:

<div id="something">
<a href="somewhere" title="something" onClick="_gaq.push(['_trackEvent', ' PDF Downloads', ‘Click', 'SEO For Beginners');">
<img>
</a>
</div>

thank you for your time; any help would be greatly appreciated

2

Answers


  1. It would be better if you just catch desired element with selector and bind a function to it, instead of binding a function directly in DOM.

    $('#something a').click(function() {
      _gaq.push(['_trackEvent', ' PDF Downloads', 'Click', 'SEO For Beginners']);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="something">
      <a href="somewhere" title="something">
        <img>
      </a>
    </div>
    Login or Signup to reply.
  2. let tag = $('#something').find('a');
    tag[0].onClick = "_gaq.push(['_trackEvent', ' PDF Downloads', ‘Click', 'SEO For Beginners')";
    

    you find the div you need by id, and by using function find() you serach your a tag.

    After that you just refer to the DOM object of your tag by tag[0] and set onClick whatever you like.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search