Gets Matching Element with a Specified Attribute in jQuery

How to select the matching element with specified attribute in jQuery ?

$("element[attribute]")

$("element[attribute]") is used to get the element with a specified attribute.

<html>
   <head>
      <title>The jQuery Example - To get matching element </title>

 <script src="https://code.jquery.com/jquery-1.10.2.js"></script>	
      <script type = "text/javascript">
        function get_element_attribute() {
        var obj = $("div[title]").html();
        var obj1 = $("div[title]").text();
        alert("Matching elements html: " + obj +"\n" + "Matching elements text: "+obj1);
        }
      </script>		
   </head>	
   <body>
<div title="this is title1">div element 1 <span>testing</span></div>
<input type="button" value="Get Element Attribute" onclick="get_element_attribute();"/>
   </body>
</html>
Output:
matching element with specified attribute output
$("div[title]").html()

Accesses html content of the matching element 'div' with an attribute 'title' and displays matching div contents.

get_element_attribute function is called when clicking on 'Get Element Attribute' button.


How to get element matching a specified attribute value ?

$("element[attribute=value]")

Gets the matching element by attribute and its value.

<html>
   <head>
      <title>The jQuery Example - To get matching element</title>

 <script src="https://code.jquery.com/jquery-1.10.2.js"></script>	
      <script type = "text/javascript">
        function get_element_attribute() {
        var obj = $("div[title='this is title2']").html();
        var obj1 = $("div[title='this is title2']").text();
        alert("Matching elements html: " + obj +"\n" + "Matching elements text: "+obj1);
        }
      </script>		
   </head>	
   <body>
<div title="this is title1">div element 1 <span>testing 1</span></div>
<div title="this is title2">div element 2 <span>testing 2</span></div>
<input type="button" value="Get Element Attribute" onclick="get_element_attribute();"/>
   </body>
</html>
Output:
matching element using specified attribute value output

Gets the matching 'div' element using attribute 'title' value 'this is title2'.

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^