0

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.

4
  • example is not class attribute it is data can you clarify this Commented Aug 12, 2016 at 4:37
  • i have updated question. Nuw you can understand Commented Aug 12, 2016 at 4:39
  • still not clear i want get second class attribute "1.png" using class one and class two. can you tell what the expected output based on what? Commented Aug 12, 2016 at 4:41
  • @Osiz4 If any of the answers were helpful please upvote and accept. Commented Aug 13, 2016 at 7:03

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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:

  • select a an element with class .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>

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.