0

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);
    }

  }
});

});
3
  • Don't use async: false; it freezes the browser. Commented May 7, 2018 at 21:31
  • 1
    You want to loop over the array. Commented May 7, 2018 at 21:31
  • And after you loop over the array, you also need to trim the text because you have spaces before and after New York City (Chelsea) Commented May 7, 2018 at 21:40

1 Answer 1

1

Using a little bit of newer javascript. You can change the content of your current success method to something like this.

const dataMap = new Map(data.map(item => [item.Store, item.URL]));
const text = $('.container p').text().trim();

if (dataMap.has(text)) { $('.container a').attr('href', dataMap.get(text)); }
Sign up to request clarification or add additional context in comments.

2 Comments

Matus, thanks! This works! Just wondering, what is dataMap.get(text)? Asking since I'm not sure how that calls item.URL.
dataMap contains (key, value) pairs such as ("New York City (Chelsea)", "URL": "/lorem/ipsum4"). When you call dataMap.get(text) with text filled with some value (key) - dataMap.get("New York City (Chelsea)") then the .get method fetches you the corresponding value, in this case "/lorem/ipsum4"

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.