Get attribute values

Hello,

I had written the code like below, is there any professional way to improves the jquery code.

Story: I want to get attribute value of first div and assign it to another one dynamically.
and right now I have added manually anchor tag for 2nd div, but i want how to add them using jquery as well.

Can i use “prop” instead of “attr”?

<!Doctype html>
<html lang=en>
<head>
<title> jQuery Snippet </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
</head>
<body>

<div id="pdp1">
<a href="https://www.google.com"><img src="img/img03.png" /></a>
<div>
<div id="pdp2">
<a href=""><img src="img/img04.png" /></a>
<div>
//<script>
	$(document).ready(function(){
		var url = $("#pdp1 a").prop('href');
		$("#pdp2 a").attr("href", url);		
		
	});
</script>//
</body>
</html>

Thanks.

Prop and attr are for two different things. Prop is for the javascript property of an object, whereas attr is the HTML attribute of an element. You can see details on the difference between them at the prop documentation page.

Most of the time they are both one and the same, but there are times where the difference matters. It’s best to use the one that’s most appropriate for the job.

In your case, using attr is the better option for retrieving the href attribute of an anchor tag.

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.