Home > Software design >  How to Convert This jQuery Code to Simple Vanilla Javascript?
How to Convert This jQuery Code to Simple Vanilla Javascript?

Time:06-21

I am trying to convert this jQuery Code into Vanilla JavaScript code. But I am unable to do.

<script>/*<![CDATA[*/$('a#password_here').attr('href', 'url_here').text('password_here').attr('style', 'visibility:visible!important;opacity:1!important;position:relative!important;z-index:1!important;font-size:14px!important;color:#fff!important;');
setInterval(function () {
    if (!$('#password_here').length) {
        window.location.href = 'url_here'
    }
}, 1000)/*]]>*/</script>

CodePudding user response:

Select the element using elem = querySelector(selector). Instead of attr use setAttribute. Instead of text use innerText. For each style do elem.style.camelCase='value'. Then finally check elem.value.length.

CodePudding user response:

Assuming your current jQuery code was working, mine should work as well. The line which tests !$('#password_here').length seems to be checking whether such an element exists, so I've converted it to vanilla JS. However, if the intention is to check the length of the content, you'll have to use my alternate code on that line (see the comment).

There's a lot about your code that is questionable at best:

It's not clear why you have two different selectors: a#password_here and #password_here. I'm assuming they refer to the same element, since IDs must be unique on a page. That's why I'm selecting a#password_here once, and using that variable in the setInterval() callback rather than selecting it again in the callback.

Even more strange: why do you need to check for the existence of an element repeatedly in setInterval()? Is some other process occasionally adding the element you're looking for? And why are you redirecting if it's not found?

<script>
let a = document.querySelector('a#password_here');
a.href = 'url_here';
a.innerText = 'password_here';
a.style = 'visibility:visible!important;opacity:1!important;position:relative!important;z-index:1!important;font-size:14px!important;color:#fff!important;';

setInterval(function() {
    if (!a) { // Might intend to say a.innerText.length instead
        window.location.href = 'url_here'
    }
}, 1000)
</script>
  • Related