Access variable outside function scope [duplicate]
This is a simplified version of what I am trying to accomplish, but I want to pass a variable outside the scope of the function. I am declaring the variable outside the function but can't get it.
HTML:
<p>5</p>
<p>6</p>
<p>7</p>
JS:
$(document).ready(function () {
var gsd = "";
$("p").each(function () {
if ($(this).text() === "5") {
var gsd = $(this).text();
alert(gsd); // this works
}
})
alert("get var outside func" + gsd); //does not work
});
Solution 1:
You redeclare gsd
as a new variable inside your function. Remove var
in front of gsd
inside the function to address the gsd
in the outer scope.