1
\$\begingroup\$

What's better - to leave the IF block blank to do nothing, or to add a statement that basically does nothing (each link already has a href attribute)?

export function fixRelativeLinksOutsideOfEpub(dom): void {
    const content = dom.window.document.querySelectorAll('a');
    content.forEach((element: HTMLElement) => {
        const href = element.getAttribute('href');
        if (href.indexOf('#') === 0) {
            // do nothing
        } else {
            element.setAttribute('target', '_blank');
        }
    });
}
export function fixRelativeLinksOutsideOfEpub(dom): void {
    const content = dom.window.document.querySelectorAll('a');
    content.forEach((element: HTMLElement) => {
        const href = element.getAttribute('href');
        if (href.indexOf('#') === 0) {
            element.setAttribute('href', `${href}`);
        } else {
            element.setAttribute('target', '_blank');
        }out
    });
}
\$\endgroup\$
3
\$\begingroup\$

You should NEVER! add superfluous or unused code.

Your code should have the single if statement checking for not equal.

    const href = element.getAttribute('href');
    if (href.indexOf('#') !== 0) {
        element.setAttribute('target', '_blank');
    }

or better yet avoid the overly complex referencing via get set attribute, and not using a search to find a known location state the whole thing becomes.

    if (element.href[0] === "#") { element.target = "_blank" }

And as a whole there is a huge amount of noise that can be removed

dom.window.document.querySelectorAll("a")
   .forEach(el => el.href[0] === "#" && (el.target = "_blank"));
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.