skip to Main Content

I have the news in an object, and i want to show them dynamically in the page.

I have a problem setting the link to each of the news – the news url is in newsArr[x].url for each news.
The following is taking each one to myPage/newsArr[x].url, but I to access the variables while writing html.

let newsArr = response.news;
let text = "<div class='bg-primary'>"
for (let x in newsArr){
    text += "<div class='card bg-body-secondary'><a href= 'newsArr[x].url'> " + newsArr[x].title + "</a></div>"
}

text+="</div>"

document.getElementById("n").innerHTML = text

4

Answers


  1. Chosen as BEST ANSWER

    Nevermind, just solved it Hope it helps anyone

    let newsArr = response.news;
    let text = "<div class='bg-primary'>"
    for (let x in newsArr){
        text += "<div class='card bg-body-secondary'><a href='" + newsArr[x].url + "'> " + newsArr[x].title + "</a></div>"
    }
    text+="</div>"
    
    document.getElementById("n").innerHTML = text
    

  2. youre going to want to change it up a bit.
    instead of putting in text to create divs, create the divs programmatically:

    const box = document.createElement("div");
    box.id = "box";
    document.body.appendChild(box);
    

    with this kind of code, you can then set the element href.
    If you do it your way, after it was added you’ll be hard pressed to be able to make changes to those divs programmatically. You lose the reference to the object since javascript is asynchronous.

    Login or Signup to reply.
  3. use string concatination to combine the static part of url with dynamic part of url

    read the below updated code and it should be easy to understand and hopefuly that should solve the problem

    let newsArr = response.news;
    let text = "<div class='bg-primary'>";
    for (let x in newsArr){
        text += "<div class='card bg-body-secondary'><a href='" + newsArr[x].url + "'>" + newsArr[x].title + "</a></div>";
    }
    text += "</div>";
    document.getElementById("n").innerHTML = text; 
    
    Login or Signup to reply.
  4. To dynamically set the href attribute of an anchor tag in JavaScript, you can concatenate the URL from the newsArr object with the string that makes up the HTML.

    Here is an updated version of your code that sets the href attribute to the url property of the newsArr[x] object:

    let newsArr = response.news;
    let text = "<div class='bg-primary'>"
    
    for (let x in newsArr){
        text += "<div class='card bg-body-secondary'><a href='" + newsArr[x].url + "'>" + newsArr[x].title + "</a></div>"
    }
    
    text+="</div>"
    
    document.getElementById("n").innerHTML = text

    This will generate the HTML with the correct URL for each news item.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search