Reputation: 49
How to get the attribute width
with in class
<div class="one" >
<img src="1.png" class="two">
<div>
<div class="three" >
<img src="2.png" class="two">
<div>
I want get second class attribute 1.png
using class one
and class two
.
Upvotes: 0
Views: 267
Reputation: 4290
Javascript has a global object named document
. You don't need JQuery to use its querySelector
function.
That object has a method called querySelector
. If you call querySelector
as a function, and pass in the classes you want to find, prepended by a .
period, it will find those elements for you.
After you have selected those elements, you can get the attribute by calling the getAttribute
method with the parameter of the attribute you need.
document.querySelector('.one .two').getAttribute('src')
More information on the queryselector can be found here
Upvotes: 1
Reputation: 73908
You can use Document.querySelector() passing a selector as a string containing one or more CSS selectors separated by commas, in this case .one > .two
which means:
.two
child of an element with class .one
.var elm = document.querySelector('.one > .two').getAttribute('src');
console.log(elm);
<div class="one" >
<img src="1.png" class="two">
<div>
<div class="three" >
<img src="2.png" class="two">
<div>
Upvotes: 1
Reputation: 5088
try with jquery like this for your edited questions
var getAttribute = $(".one .two").attr("src");
alert(getAttribute);
see the demo
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="one" >
<img src="1.png" class="two">
</div>
</body>
<script type="text/javascript">
var s = $(".one .two").attr("src");
alert(s);
</script>
</html>
Upvotes: 1