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
Nevermind, just solved it Hope it helps anyone
youre going to want to change it up a bit.
instead of putting in text to create divs, create the divs programmatically:
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.
use
string concatination
to combine the static part of url with dynamic part of urlread the below updated code and it should be easy to understand and hopefuly that should solve the problem
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:
This will generate the HTML with the correct URL for each news item.