1

I'm looping through some data with a var called sortedlist[i].description that contains an URL. I need to build the following HTML output:

<div onclick="location.href='http://XXXXXX' class="MusicItem">

I'm building my HTML output with a var called output which accumulates into the full body of my page.

output += '<div onclick="location.href="' + 
          sortedlist[i].description + '" class="MusicItem">';

The above of course breaks. I clearly have an issue with my quotation usage/syntax but I've tried it every which way:

  1. alternating single to double quotes.
  2. only using single quotes. and
  3. using parens in place of the single quotes, etc.

Nothing is working.

1
  • 3
    If you want an element with the functionality of linking somewhere else on click - then why don't you use an actual link? '<a href="...">' requires one less "level" of string delimiters. Commented Sep 10, 2016 at 19:06

3 Answers 3

1

You can escape the quotes like this:

output += '<div onclick="location.href=\'' + sortedlist[i].description + '\'" class=\"MusicItem\"></div>';

Generating the following string:

<div onclick="location.href='https://google.com'" class="MusicItem"></div><div onclick="location.href='http://stackoverflow.com'" class="MusicItem"></div>
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

output += '<div class="MusicItem" data-url="'+sortedlist[i].description+'"></div>'

and attach a click event like this

var item = document.querySelectorAll(".MusicItem");

    for(var i = 0;  i < item.length; i++){
        item[i].addEventListener("click", function(event){
            window.location.href = this.dataset.url;
        });
    }

or if you just want to redirect to new page on click event then better use an anchor tag

Comments

0

possible solution is

output += sortedlist.map(function(item){
    return '<a href="'+item.description+'" class="MusicItem">' 
});

Comments

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.