Need to make a webpart which gets data from API in JSON format. I generate a table from JSON with projects number. Then I change each td to link with class="project_number".
Now each position has it's specific class. No I need each link to direct to project details ot url like: https://XXX.azurewebsites.net/api/protocollines?protocolNo=PR0002
I don't know what parameter should I place in querySelector to have addEventListener for each link.
document.querySelector("???").addEventListener('click', *function*);
function changeToLink(){
var tableCells = Array.from(document.getElementsByTagName('td'));
var i;
var proNo = "PR0";
for (i=0; i<tableCells.length; i++ && isContains == true) {
var proFromArray = tableCells[i].innerHTML;
var isContains = proFromArray.includes(proNo);
if(isContains == true){
var tdElement = document.getElementsByTagName('td')[i];
console.log('Profrom: ' + proFromArray);
tdElement.innerHTML = `<a class="${proFromArray}" href='https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}'>${proFromArray}</a>`
}
}
}
document.querySelector(`??`).addEventListener('click', *function*);
There's a few ways to do this.
Option 1You could create the anchor elements using JS, and add the onclick event when you create each one, like:
I created a Fiddle to demonstrate how it works: https://jsfiddle.net/brettnolf/f3xd7ag1/
Option 2Now, if you need to create it in the form of a string and later call
querySelector
on what you created, you could add the same class to each anchor tag:Then add the event listener, like:
Option 3If both of those solutions are out of the question, you could use a query selector wildcard and add the event listener similar to the above:
You can see this last solution in action if you pull up Chrome dev tools here https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll and enter
document.querySelectorAll('[class^=title]')
in the Console.Note that the last two options will only work after the elements have been added to the DOM. In the first option, you add the listener when you create the element, so you do it on the fly.