Osiz 4
Osiz 4

Reputation: 49

How do I get the width attribute via class selector?

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

Answers (3)

David Guan
David Guan

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

GibboK
GibboK

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:

  • 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>

Upvotes: 1

caldera.sac
caldera.sac

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

Related Questions