Conver current jQuery code to valid vanilla Javascript - javascript

I have this jQuery code, but I need to convert it to vanilla Javascript because the project I am working on is not using jQuery
Here is what I have tried, but it is not working. I am unsure for all of these changes that I have made
// My current jQuery code
$('#category-2 ul li').each(function() {
$(this).find("ul.top-menu").parent().remove();
});
$('#category-2>a').html("Produkte");
// Vanilla JS
document.querySelectorAll('#category-2 ul li').forEach(function() {
this.find('ul.top-menu').parentNode().removeChild();
});
document.querySelectorAll('category-2>a').innerHTML="Produkte";

There are several problems in your code. One is that in the function you are using the this keyword as it would be in a class, but in functions the this keyword does not refer to what you would expect it to be. Instead use parameters from the forEach function: item, index, array, thisArg can be used.
The second problem is that in Vanilla JS there is no find() method so I would suggest implementing a ternary operator (one line if statement) to check if the className or the id includes what you are searching for.
I'm not sure what items are you searching for without the html it is hard to tell, but it would look something like this:
// Vanilla JS
document.querySelectorAll("#category-2").forEach(item => {
item.className.includes("top-menu") && item.parentNode.removeChild();
});
document.querySelectorAll("#category-2").forEach(item => {
item.innerHTML = "Produkte";
});

Related

Adding event listeners to multiple input elements using plain JS (not jQuery)

I have a code block that works perfectly in jQuery but it's the last bit of a project I am converting to plain vanilla Javascript with the specific aim to remove any and all dependencies on jQuery.
Here is the existing code block at issue:
$("input[data-pattern='comma']").on({
keyup: function() {inputComma($(this));}
});
How do I achieve this same functionality using ONLY plain pure JS?
Note: inputComma is a custom handler that conforms the value for EACH input element instance to a comma-delimited regex pattern as the user is typing.
If it helps, I tried...
document.querySelectorAll("input[data-pattern='comma']").forEach(function(elem) {
elem.addEventListener("keyup", function() {inputComma(elem);});
});
and also...
document.querySelectorAll("input[data-pattern='comma']").forEach(function(elem) {
elem.addEventListener("keyup", () => {inputComma(elem);});
});
I know jQuery's $(this) is different from "this" and that arrow functions also materially affect which "this" is being referenced. I tried to get around that issue by referencing the iterating object but I think that may be part of my problem. Not opposed to using the "this" pointer if there is a way to make it work in pure JS.
Thanks in advance for your help!
I think this can be better done using event delegation. It would look something like:
document.addEventListener(`keyup`, handle);
function handle(evt) {
if (evt.target.dataset?.pattern === `comma`) {
return inputComma(evt.target);
}
}
function inputComma(elem) {...}

Piece of jQuery code to enable class selector?

I am not using jQuery, but I have one line of code that enables the $ selector shortcut, as follows:
let $ = function (id) { return document.getElementById(id); }
I would like to also add whatever code necessary so that I can use the class selector shortcut as well.
Right now I have this:
let $c = function (cl) { return document.getElementsByClassName(cl); }
And I can select elements by class with $c("some-class"), but that returns a list that I need to then cycle through.
I would like to be able to use stuff like $(".some-class").remove("some-class") - to remove the class from all elements that have it without having to have a loop cycle through the list and remove them one by one.
Could anyone point me toward the part of jQuery that does that so I can include it and not the entire library?
I tried looking through the jQuery code for the term className but there are 39 instances and I'm not sure which part I need.
The closest thing native JS has to jQuery's sizzle selector engine is querySelector() or querySelectorAll(), depending on whether you're expecting a single element to be found, or multiple.
In your example, this would be:
let $ = selector => document.querySelectorAll(selector);

How to click a pop up using code

I've just gotten into code and made this
setInterval(function() {
if ($('Text').is(":visible") === true) {
document.getElementById('text').getElementsByClassName('Yes').Click();
} }, 5000);
I don't think it works and probably has a lot of problems with it and I don't know how to fix it.
What are you going to achieve?
document.getElementById('text').getElementsByClassName('Yes').Click();
won't works, because
document.getElementById returns just one element, you can access to its
children using children property (or childNodes).
getElementsByClassName returns common array of elements. If you read some JS tutorial you should know how to access it.
HTMLElement have no Click() method, but click()
Also you shouldn't mix pure JS with jQuery.

Creating a small jQuery plugin

I created this plugin to make work around an application easier.
Here is the link : http://jsfiddle.net/X5Squ/
My problem it that it always uses just 1 of the elements, please don't edit the data and data5 functions as these work perfectly for other parts but I need my function called jtoggle to work.
Any help much appreciated! Thanks.
$(document).ready(function (){$('.jtoggle').jtoggle(true);});
Have you tried using .each on this? I think the issue is that it isn't passing an array of DOM elements. I lack much experience in creating plugins, but it seems this can be easily averted by doing the following:
$(document).ready(function (){
$('.jtoggle').each(function(){
$(this).jtoggle(true);
});
});
(Which would also mean that you can safely remove the .each you have in jtoggle itself)
In your plugin you should act on each matched element and then return all the matched elements in order to maintain chainability:
$.fn.jtoggle = function (addUnderline) {
return this.each(function () {
// Do what you need on this matched element
});
};
Maintaining chainability means we can do stuff like:
$(".jtoggle").jtoggle(true).addClass("xyz");

Using jQuery in a JavaScript function

function divlightbox(val)
{
if(val)
{
val=val.replace( /^\s+/g, "" );
var count_js=0;
var big_string='';
document.getElementById("video_lightbox").innerHTML="";
document.getElementById("divlightbox").style.display = "block";
$("#video_lightbox").css({"height":"430px","top":"10%","width":"480px"});
I found out that the error is in the above. My question is can't I use jQuery and traditional JavaScript at same time? I have done coding like this numerous times and never ran into a problem like this. I used to use jQuery methods like .hide() and .css() inside JavaScript functions but this time it doesn't work.
Thanks in advance.
While the other answers fix the specific problems, I don't think the OP's question (in bold) is really answered here, as depending on the specific context, $ may possibly not be defined as a jQuery object yet (having had this problem myself a few times now.)
In which case you would need to do something like:
function divlightbox(val) {
// ...
// just use jQuery instead of $ one time
jQuery("#video_lightbox").css({"height":"430px","top":"10%","width":"480px"});
}
OR
function divlightbox(val) {
// define the $ as jQuery for multiple uses
jQuery(function($) {
// ...
$("#video_lightbox").css("height":"430px");
$("#video_lightbox").css("top":"10%");
$("#video_lightbox").css("width":"480px");
});
}
jQuery is JavaScript so YES. Instead .innerHTML="" just use .empty(). Instead .getElementById() use $('#..') and so on.
to do things like hide(); and css() you need jquery objects. you can't do them to dom elements.
so you could do $('#video_lightbox').html("");
or
$('#video_lightbox').empty();
You must provide error in javascript console.
1) Do you pass a val argument to divlightbox function()? When do you call it?
2) why do you use the same identifier divlightbox both for a function and for a div id? Change name to the function please, maybe the problem could be here.
3) Always check if video_lightbox and divlightbox exist before accessing them.

Categories