I'm trying to see if an HTML element has a matching text in a JSON file, then change the link on the page according to the JSON. So for example, if the p tag contains New York City (Chelsea), change href to /lorem/ipsum1. I think I have the logic correct but I know I'm not executing it correctly.
Also note that within the p tag, there could be a space before and/or after the location name.
Thanks ahead for the insight!
https://codepen.io/anon/pen/yjPZaK
JSON
[
{
"Store": "New York City (Upper East Side)",
"URL": "/lorem/ipsum1"
},
{
"Store": "Lincoln Square",
"URL": "/lorem/ipsum2"
},
{
"Store": "New York",
"URL": "/lorem/ipsum3"
},
{
"Store": "New York City (Chelsea)",
"URL": "/lorem/ipsum4"
},
{
"Store": "Harlem",
"URL": "/lorem/ipsum5"
}
]
HTML
<div class="container">
<p> New York City (Chelsea) </p>
<a href="/original/link">Link</a>
</div>
JS
$(function() {
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/7lu0y",
async: false,
success: function(data){
if ($('.container p').text() == data.Store) {
$('.container a').attr('href', data.URL);
}
}
});
});
async: false; it freezes the browser.trimthe text because you have spaces before and afterNew York City (Chelsea)