skip to Main Content

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


  1. You can use

    var withAlias = document.querySelectorAll("a[alias]");
    

    To get all anchor tags that have the alias attribute. Using this, you can do

    withAlias.forEach(function(aTag) {
      // run your regex on aTag.getAttribute("[alias]");
      // to determine correctness
    });
    

    To get all anchor tags that don’t have an alias attribute, you can do

    var noAlias = document.querySelectorAll("a:not([alias])");
    

    Most folks would agree that it is easier to see what you are doing this way

    Login or Signup to reply.
  2. 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.

    function eval(ctxt) {
      let links = ctxt.querySelectorAll('a');
      console.table(links);
      links.forEach(l => {
        let alias = l.getAttribute('alias');
        if (alias == null) {
          console.log(l.innerText + ' does not have alias');
        } else {
          console.log(l.innerText + ' alias is ' + alias);
        }
      })
    }
    //set initial textbox value 
    document.getElementById('textField').value = '<a href="www.test.net" alias="test.net">Testing</a><br/><a href="www.e2d2.ca">Dont go here!</a>';
    
    //mockup and connect button
    document.getElementById('eval').addEventListener('click', (e)=>{
    // copy to context, load
    let ctxt = document.getElementById('ctxt');
    ctxt.innerHTML = "";
    ctxt.innerHTML = document.getElementById('textField').value;
    //evaluate against the context element
    eval(ctxt);
    });
    <textarea id="textField" type="text"></textarea><button id=eval>Evaluate</button>
    <context id='ctxt' style='display:none'></>

    https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

    Login or Signup to reply.
  3. You can simplify this using fragments. Please do not use regex

    document.addEventListener("DOMContentLoaded", function() {
      const checkButton = document.getElementById("checkButton");
      const resultDiv = document.getElementById("result");
    
      checkButton.addEventListener("click", function() {
        const htmlCode = document.getElementById("htmlInput").value;
        const fragment = document.createElement("div");
        fragment.innerHTML = htmlCode;
        const aliasMatches = fragment.querySelectorAll("a[alias]");
        // Initialize arrays to store errors and warnings along with line numbers
        const invalidAliases = ["Invalid Aliases:"];
        const missingAliases = ["Missing Aliases:"];
        const noAliasMatches = fragment.querySelectorAll("a:not([alias])");
        if (noAliasMatches.length > 0) noAliasMatches
          .forEach((match, i) => missingAliases.push(`Missing alias for with href = "${match.href}"`));
    
        // Loop through each line and check for <a> tags with alias attributes
        aliasMatches.forEach((match, i) => {
          const alias = match.getAttribute("alias");
          if (alias === "") {
            missingAliases.push(`Empty alias for link with href = "${match.href}"`);
          } else if (!/^[a-zA-Z0-9_]+$/.test(alias)) {
            invalidAliases.push(`Invalid alias "${alias} for link with href = "${match.href}"`);
          }
        });
    
        // Generate result messages
        let resultMessage = [];
    
        if (missingAliases.length > 1) resultMessage = resultMessage.concat(missingAliases);
        if (invalidAliases.length > 1) resultMessage = resultMessage.concat(invalidAliases);
    
        if (resultMessage.length === 0) resultMessage = ["All aliases are in the correct format."];
        resultDiv.innerHTML = resultMessage.join("<br/>");
      });
    });
    <textarea id="htmlInput"><a href="bla" target="_blank"
    alias="Hello" 
    >Visit bla</a>
    
    <a href="bla1" target="_blank"
    alias="" 
    >Visit bla1</a>
    
    <a href="bla2" target="_blank"
    >Visit bla2</a>
    
    
    </textarea>
    <button type="button" id="checkButton">Check</button>
    <div id="result"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search