2
Answers

Get anchor tags value using jQuery

Photo of Har Kaur

Har Kaur

7y
265
1
My friend had an interview few days ago and they asked to him about Jquery.
So, the question is like: Suppose i have 10 anchor tag in my html and out of 10 anchor tags 5 have the class property. So, how can you get the anchor tags value that have not any class property?

Note: Any type of chnage in html is not acceptable. You should get tha anchor tag value without change anything in html.
 
Can anyone tell how this is possible. Please !! 

Answers (2)

2
Photo of Rehman Shahid
NA 1.1k 148.1k 7y
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.   <script data-require="jquery@3.1.1" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>  
  6. </head>  
  7.   
  8. <body>  

  9.     <a href="#" class="anchor">class anchor1</a>  
  10.     <a href="#" class="anchor">class anchor2</a>  
  11.     <a href="#" class="anchor">class anchor3</a>  
  12.     <a href="#" class="anchor">class anchor4</a>  
  13.     <a href="#" class="anchor">class anchor5</a>  
  14.     <a href="">non-class anchor1</a>  
  15.     <a href="">non-class anchor2</a>  
  16.     <a href="">non-class anchor3</a>  
  17.     <a href="">non-class anchor4</a>  
  18.     <a href="">non-class anchor5</a>  

  19.   
  20.   <script>  
  21.     $(document).ready(function() {  
  22.   
  23.       //getting all anchors that have no any class property  
  24.       var allNonClassAnchors = $("a:not([class])");  
  25.   
  26.       //getting values of all anchors that have no any class property  
  27.       var values = [];  
  28.       $.each(allNonClassAnchors, function(i, val) {  
  29.         values.push(val.text);  
  30.       });  
  31.         
  32.       //displaying values of all anchors that have no any class property  
  33.       alert(values.join());  
  34.     });  
  35.   </script>  
  36. </body>  
  37.   
  38. </html>  
Accepted
1
Photo of Manas Mohapatra
NA 29.3k 3.3m 7y
It's simple, have a look:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     $("a[href$='.org']").css("background-color", "yellow");});  
  8. </script>  
  9. </head>  
  10. <body>  
  11.   
  12. <a href="https://www.w3schools.com">w3schools.com</a><br>  
  13. <a href="http://www.google.com">Google.com</a><br>  
  14. <a href="http://www.wikipedia.org">wikipedia.org</a>  
  15.   
  16. </body>  
  17. </html>  
 https://www.w3schools.com/jquery/jquery_ref_selectors.asp