Consider:
document.addEventListener("DOMContentLoaded", function () {
const checkButton = document.getElementById("checkButton");
const resultDiv = document.getElementById("result");
checkButton.addEventListener("click", function () {
const htmlCode = document.getElementById("htmlInput").value;
// Split the HTML code into lines for line number tracking
const lines = htmlCode.split('n');
// Regular expression pattern to match <a> tags with alias attributes
const aTagPattern = /<a[^>]*alias="([^"]*)"/g;
const aliasMatches = [];
// Initialize arrays to store errors and warnings along with line numbers
const invalidAliases = [];
const missingAliases = [];
// Loop through each line and check for <a> tags with alias attributes
lines.forEach((line, lineNumber) => {
const aTagMatches = [...line.matchAll(aTagPattern)];
aTagMatches.forEach((match) => {
const alias = match[1];
if (!/^[a-zA-Z0-9_]+$/.test(alias)) {
invalidAliases.push(`Invalid alias "${alias}" on line ${lineNumber + 1}`);
}
});
if (!line.includes('alias=')) {
const hrefMatch = line.match(/<a[^>]*href="([^"]+)"/);
if (hrefMatch) {
const href = hrefMatch[1];
missingAliases.push(`Missing alias for href="${href}" on line ${lineNumber + 1}`);
}
}
});
// Generate result messages
let resultMessage = "";
if (missingAliases.length > 0) {
resultMessage += "Missing Aliases:n" + missingAliases.join('n') + "n";
}
if (invalidAliases.length > 0) {
resultMessage += "Invalid Aliases:n" + invalidAliases.join('n') + "n";
} else if (missingAliases.length === 0) {
resultMessage = "All aliases are in the correct format.";
}
// Display the result message
if (resultMessage !== "") {
resultDiv.innerText = resultMessage;
} else {
resultDiv.innerText = "HTML code is valid!";
}
});
});
This is my JavaScript code. The main function is to check for the alias attributes in and if the alias is missing, it gives an error or not in the proper format.
It takes HTML code as input. It works fine, but if the alias is in the next line, it is not considering it giving no alias found error. How can I fix it?
Correct output if the alias is in the same line:
Wrong output if the alias in the next line:
3
Answers
You can use
To get all anchor tags that have the alias attribute. Using this, you can do
To get all anchor tags that don’t have an alias attribute, you can do
Most folks would agree that it is easier to see what you are doing this way
Using the built in selector and getAttribute, you can loop through the elements and check for the existence of alias attribute.
UPDATE: now uses a text input field, and copies to a hidden element for evaluation when clicking the button.
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
You can simplify this using fragments. Please do not use regex