繁体   English   中英

用新的标签内容替换 html 标签

[英]Replace html tag with new tag content

页面的 html 标签没有 lang=en 属性,我试图将它添加到 html 标签,下面是我做的代码,但它替换了整个 html 内容,而不是仅仅将 lang=en 添加到 html。

window.addEventListener('load', function () {
    alert("It's loaded!")
    const cond = document.getElementsByTagName('html')[0]|| false;
    console.log(cond)
     if (cond) {
          $('html').each(function() {
              $(this).replaceWith($('<html lang="en">'));
          });
    }});

我也尝试了下面的代码,但它也不起作用,基本上它获得了 html 内容,并附加了新的 html 标签和内容。

const htmlContent = $( "html" ).html();
    if (cond) {
        $('html').replaceWith('<html lang="en">' + htmlContent +  '</html>');
    }

使用香草 JS 的可能解决方案可能是。

document.querySelector('html').setAttribute("lang", "en")

使用attr方法。

$(this).attr("lang", "en");

这不是这样做的最佳方式,因为它可能导致事件分离或其他性能问题。 这样做会更安全:

$('html').attr('lang', 'en')`

这样你只添加一个属性,没有别的。

根据您的代码,您可以尝试使用 vanilla js:

<script>
let domHTML = document.getElementsByTagName('html')[0];
let lang = domHTML.getAttribute('lang');
console.log('lang: ' + lang);
domHTML.setAttribute('lang', 'fr');
lang = domHTML.getAttribute('lang');
console.log('lang: ' + lang);
</script>

请参阅有关使用此属性方法的setAttributegetAttribute的详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM