Jay
Jay

Reputation: 49

How do I access anchor tag in JavaScript?

I want to access this anchor tag in JavaScript:

<a href="#" class="pull-right"> Edit </a>

At the moment the HTML where it is located looks like this:

<div class="about_section">
    <div class="col-md-5">
        <div class="panel panel-default">
            <div class="panel-heading">
                <a href="#" class="pull-right"> Edit </a>
                <h3 class="panel-title"> About You </h3>
             </div>
            <textarea id="about_me" class="form-control inputstl" rows="5"> </textarea>
        </div>
    </div>
</div>

Now I have tried to access this anchor tag via the following route in my JavaScript:

$('.about_section').find('a.pull-right').eq(0).on('click', function() {
    console.log('Works');   
})

This did not work, and also via this route:

$('.about_section').find('col-md-5').find('panel panel-default').find('panel-heading').find('a').eq(0).on('click', function() {
    //$('#edit-modal').modal()
    console.log('Works');
})

This did not work either, anyone have any suggestions?

Upvotes: 0

Views: 3015

Answers (4)

SpYk3HH
SpYk3HH

Reputation: 22570

So many people here missing so much. One of your first problems is not your anchor tag, but your selectors. .find('col-md-5') won't find anything because you just told it to find an Anchor Tag named col-md-5. You forgot the period (.). You can use selectors in jQuery much the same way you use them in CSS.

Also, you have to be careful of spacing. Even if you included the periods, .find('.panel .panel-default') would still not find anything because the element that has the class panel is the same one having the class panel-default. That space tells jQuery "Find an element having class panel with sub-elements having class panel-default"

What your line should look like:

$('.about_section').find('.col-md-5').find('.panel.panel-default').find('.panel-heading')

The following should work fine:

$('.about_section a.pull-right').on('click', function() {
	console.log('Works');	
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="about_section">
	<div class="col-md-5">
		<div class="panel panel-default">
			<div class="panel-heading">
				<a href="#" class="pull-right"> Edit </a>
				<h3 class="panel-title"> About You </h3>
			 </div>
			<textarea id="about_me" class="form-control inputstl" rows="5"> </textarea>
		</div>
	</div>
</div>

However, there are several ways to fully answer your question as well as several ways this can be better achieved.

You're initial question title has many routes for answers.

  1. To get all anchor tags in pure JavaScript: var a = document.getElementsByTagName('a')
  2. To get all anchor tags in jQuery: var a = jQuery('a')
  3. To get a specific anchor by ID, Class, Or Name in vanilla JS:
    • . document.getElementById('ele_id_atr_val')
    • . document.getElementsByClassName('class-name')
    • . document.getElementsByName('ele_name_atr_val')
    • Keep in mind, with Class and Name, it will get all elements having those attribute values.
  4. To get a specific anchor by ID, Class, Or Name in vanilla jQuery:
    • . jQuery('#ele_id_atr_val')
    • . jQuery('.class-name')
    • . jQuery('[name=ele_name_atr_val]')
    • Keep in mind, with Class and Name, it will get all elements having those attribute values.

With all the basics out of the way, let's look at how we can improve upon what you're doing. You want to add an on_click event to an anchor element. First, let's start with the "action" or the href attribute. You're using the typical, and often recommended #, however, I would assert this is a bad practice. There's various reasons, but this answer here wraps it up pretty well. I would suggest setting your href attribute to href="javascript:void(0)". That ensures no falsy calls or unexpected behavior when the anchor is clicked on.

Next, let's discuss "event handlers" and a better establishment thereof. You're making use of .eq(), which will ensure the event is assigned to only one item, but is this really your intent? And if so, then why all the build up? Why not give that one item a unique id and assign the event based on that selector? Also, you're driving through 50 miles of hay to get to a store just around the corner. A personal rule I use, if the selector to my event handler looks like a full sentence on an essay paper, it's too long. The point of jQuery, and even vanilla JS' querySelector is to make things easier. Simplify the matter.

So your selector to your event should be as simple as:

$('.about_section .pull-right').on('click', function(e) {

This sums it up nice. It provides a parent element, the about_section block, as well as it's coordinating child of which we want to apply the event. Now that we have this much, let's make it even better and discuss "dynamic event handling". Known in jQuery as the .on|.off method.

By using jQuery's .on method in conjunction with thinking about "dynamic handling" (dealing with elements added after document.readyState="complete", we can write more powerful event delegation statements that better well suit our purpose as well as provide easier readability to those who might be reviewing and/or editing our code in the future.

There are two main ways of setting up such dynamics. The first, and most recommended, is to use a static (always there when page loads) element and assign it a child with an event. Such as:

$('.about_section').on('click', '.pull-right', function() {
    console.log('Works');   
});

Here, we count on an element having the class about_section to be the parent element always available when the page loads. Basically, this parent is then told "Hey! Hey you! Yes you! Every time you have a kid with the class pull-right, tell that kid to do this thing!" And so it does. Whether added on page load, or five minutes after the page is loaded, the kid having class pull-right will always do as it's parent says. This is different from my previous suggestion of $('.about_section .pull-right') in that it will apply to such dynamic (added after load) elements, whereas the previous one will only work on all those elements that exist when the page loads.

The second main way, my preferred, but considered a "dangerous memory" issue by others, is to use $(document).on. First, understand it's not a danger it that it will hurt your app or other computers. It's simply unfavored because it's a danger to the run time memory. In simplest of terms, mostly with days of old (and ancient devices) assigning everything to the document variable could slow the page down. This is generally no longer an issue and for five+ years now I've been using this method with everything from basic business websites to top end, classified military apps I made for the army. Don't ask, I won't tell.

Anyway, I prefer this method because it also provides an easy way to organize a whole list of events, as well as maintain the power of dynamic handling, which is so often needed in today's world of "live pages".

$(document)
    .on('click', '.about_section .pull-right', function() {
        console.log('Works');   
    })
    .on('event', 'selector', function(e) { /*   Easily      */ })
    .on('event', 'selector', function(e) { /*   Organized   */ })
    .on('event', 'selector', function(e) { /*   And     */ })
    .on('event', 'selector', function(e) { /*   Easy    */ })
    .on('event', 'selector', function(e) { /*   To      */ })
    .on('event', 'selector', function(e) { /*   Read    */ })
    .on('event', 'selector', function(e) { /*   For     */ })
    .on('event', 'selector', function(e) { /*   Future  */ })
    .on('event', 'selector', function(e) { /*   Devs    */ })

Any questions?

Upvotes: 0

sa77
sa77

Reputation: 3603

you can use HTML onclick event attribute to trigger a JS function. For example in this case. onclick='test();' on the anchor tag triggers JS method test() method defined on the page.

<script>
  function test() {
    console.log('works');
  }
</script>

<div class="about_section">

  <div class="col-md-5">

    <div class="panel panel-default">

      <div class="panel-heading">

        <a href="#" class="pull-right" onclick='test();'> Edit </a>

        <h3 class="panel-title"> About You </h3>

      </div>

      <textarea id="about_me" class="form-control inputstl" rows="5"></textarea>

    </div>

  </div>

</div>

Upvotes: 0

Vijaya Vignesh Kumar
Vijaya Vignesh Kumar

Reputation: 444

Try this

<div class="about_section">

<div class="col-md-5">

<div class="panel panel-default">

    <div class="panel-heading">

        <a href="#" class="pull-right" onclick="fun();"> Edit </a>

        <h3 class="panel-title"> About You </h3>

     </div>

        <textarea id="about_me" class="form-control inputstl" rows="5"> </textarea>

</div>

</div>


<script>
     function fun () {
         console.log("works");
     }
</script>

Upvotes: 0

brk
brk

Reputation: 50291

You can simply do by using

document.querySelectorAll("a.pull-right");

Also you can do like this

$(".about_section a.pull-right").on('click',function(){
//rest of code
})

Upvotes: 1

Related Questions