o.addClass is not a function - javascript

I want to get the ID of the clicked anchor and add a class to the element with same ID.
$galleryItem.click(function(e){
e.preventDefault();
var $galleryProjectContent = $(this).attr("id");
console.log($galleryProjectContent);
$galleryProject.addClass('d-block slideInUp animated');
$body.css('overflow', 'hidden');
$galleryProjectContent.addClass('d-block');
});
I get:
Uncaught TypeError: o.addClass is not a function.

This code is the problem:
var $galleryProjectContent = $(this).attr("id");
$galleryProjectContent is a string, not a jQuery object or a DOM element.
You've said:
I want to get the ID of the clicked anchor and add a class to the element with same ID.
There's no reason to get the ID and then look up the element with the ID, you already have the element: this. It has to be the element you're looking for (since id values must be unique on the page). To get a jQuery wrapper for it, just use $(this). So simply:
var $galleryProjectContent = $(this);
If you needed to get an element by an ID that you have as a string, you could do it like this:
var $x = $("#" + theId);
// or
var $x = $(document.getElementById(theId));
But again, there's no reason to do that here.

Related

Updating id attribute using $(this) not working jquery

I'm using JQuery clone() method to clone form and updating form input value's "id" attribute increment by 1.
Everything is going perfect but I'm curious about $(this) and this.
In clone() -> each() method while updating input id I've faced issues like when I'm updating value like:
this.id=newId; then its working and updating id attribute
But if I use $(this).attr(oldId,newId) then its not working
If I use var old=newId then also its not working
I've referred this and this but still confused why last two methods are not working.
Full code:
var clonedTemplate = $(".form-section .row:first").clone();
var index = 0;
$("body").on('click', '.add', function () {
index++;
var formSection = clonedTemplate.clone().find(':input').each(function () {
var oldId = $(this).attr('id');
var newId = oldId + "_" + index;
this.id=newId; //its working and updating id attribute
$(this).attr(oldId,newId) // not working
oldId=newId; // not working
});
formSection.end().appendTo('.form-section');
});
Any help/suggestion or better solution would be appreciated.
you need to pass in the name of the attribute you are altering, not the value of it so this line
$(this).attr(oldId,newId)
needs to become
$(this).attr('id',newId)

jQuery: HIde prev and next div after a click event

My goal is to hide the prev or next div after clicking on a li element.
This is the script:
jQuery('.menu-ul li').on('click',function(){
var current_id = jQuery(this).data('id');
var menu_id = '#' + current_id;
jQuery(menu_id).next("div").attr("id").hide()
jQuery(menu_id).prev("div").attr("id").hide();
});
The script above works fine, but when I put the function hide() I get this error:
Uncaught TypeError: jQuery(...).next(...).attr(...).hide is not a function
How can I solve it?
To ge the previous element use $(selector).prev(), and to get the next use $(selector).next(). Then use .hide() to hide any, or both of them.
Like this:
jQuery('.menu-ul li').on('click',function(){
var current_id = jQuery(this).data('id');
// We get the element and store it, so we don't get it twice later.
var element = jQuery('#' + current_id);
element.prev().hide();
element.next().hide();
});
try following code,
jQuery('.menu-ul li').on('click',function(){
var current_id = jQuery(this).data('id');
var menu_id = '#' + current_id;
jQuery(menu_id).next("div").hide()
jQuery(menu_id).prev("div").hide();
});

What are the equivalent of after and before jQuery's function in native javascript?

I always used jQuery before, but I want to switch the following to native javascript for better performance of the website.
var first = $('ul li:first');
var first = $('ul li:last');
$(last).before(first);
$(first).after(last);
From: http://clubmate.fi/append-and-prepend-elements-with-pure-javascript/
Before (prepend):
var el = document.getElementById('thingy'),
elChild = document.createElement('div');
elChild.innerHTML = 'Content';
// Prepend it
el.insertBefore(elChild, el.firstChild);
After (append):
// Grab an element
var el = document.getElementById('thingy'),
// Make a new div
elChild = document.createElement('div');
// Give the new div some content
elChild.innerHTML = 'Content';
// Jug it into the parent element
el.appendChild(elChild);
To get the first and last li:
var lis = document.getElementById("id-of-ul").getElementsByTagName("li"),
first = lis[0],
last = lis[lis.length -1];
if your ul doesn't have an id, you can always use getElementsByTagName("ul") and figure out its index but I would advise adding an id
I guess you are looking for:
Element.insertAdjacentHTML(position, text);
Where position is:
'beforebegin'.
Before the element itself.
'afterbegin'.
Just inside the element, before its first child.
'beforeend'.
Just inside the element, after its last child.
'afterend'.
After the element itself.
And text is a HTML string.
Doc # MDN
You can use insertBefore():
var node = document.getElementById('id');
node.parentNode.insertBefore('something', node);
Documentation: insertBefore()
There is no insertAfter method. It can be emulated by combining the insertBefore method with nextSibling():
node.parentNode.insertBefore('something', node.nextSibling);

get a value with a jquery for loop

I have several item in a databse, I'm displaying a link with in the href the id of each item.
So I want to get the id from a href which is in a PHP while loop. So I did a for loop to do it but it seems to only get the first href attr.
for (var i = 0; i < check; i++)
{
var id = $(".id").attr('href');
console.log(id);
}
Check is equal to the number of columns in the database depends of a special id. In this case check = 3
The link is: echo '<a id="dislike" class="btn-primary btn pull-right id" href="'.$items['id'].'">Dislike</a>';
Any idea of why it doesn't work ?
I got them all!
But how can I make them go out of the function ?
function checkingfetchresult(userid){
$.post("ajax/checkingfetchresult.php", { userid: userid },
function(check){
$(".id").each(function(){
var id = $(this).attr('href');
});
});
}
You are selecting the same elements on each iteration and then getting the attribute of the first element in the set. Instead of looping like that, you should use each:
$(".id").each(function(){
var id = $(this).attr('href');
console.log(id);
});
You're getting the first element every time, and logging its href. You can't expect a loop to behave differently if it's doing the same thing every time?
If you want to get all the href attributes for all the .id elements, use map:
$('.id').map(function () { return $(this).attr("href") });
It will return an array, where each element is the href of the corresponding .id element.
$(".id") returns an array-like object, containing all of the matching elements. what you actually want to do is this:
var idArray = $(".id");
for (var i = 0; i < check; i++) {
var id = $(idArray[i]).attr('href');
console.log(id);
}

Access a label's attribute using jquery

I have some data coming from the server in which I fill A Div in the Html page with.
The way I write the div is as follows:
<div class="BigDiv"><label class = "AttList" Std_Id="' + Std_Id + '">' + Std_Name +'</label></div>
Now, I want the data inside this div.
There are some other labels inside the div so I use this.children to access this label.
var labels = $(this).children('div');
var StdName = this.children[0].childNodes[0].nodeValue;
I want to access the Std_Id inside the Std_Id attribute, but I don't know how to do it ... Do you have any ideas?
Thanks.
Assuming that $(this) is a reference to the .BigDiv element:
var StdName = $(this).find('label').attr('Std_Id');
Or, similarly, and with the assumption that this is the .BigDiv element:
var children = this.childNodes;
for (var i=0,len=children.length; i<len; i++){
if (children[i].nodeType == 1 && children[i].tagName.toLowerCase() == 'label'){
var StdName = this.getAttribute('Std_Id');
}
}
References:
jQuery:
attr().
find().
JavaScript
element.getAttribute().
node.nodeType.
tagName.
toLowerCase().
Use getAttribute:
var labels = $(this).children('div');
var StdId = this.children[0].getAttribute("Std_Id");
Note that, according to the HTML5 spec, custom attributes should start with data-, though most browsers can tolerate it.
To save elements, which were selected using a jQuery-Selector, do this:
$labels = $('.BigDiv').find('label');
Now you can loop through each label with jQuery's foreach loop:
$.each($labels, function() {
var std_id = $(this).attr('Std_Id');
// do something with std_id
});
You could use the attr method as such,
var value = $('.AttList').attr('Std_Id');
EDIT
OK, so you for your implementation, you need to do this...
var value = $(this).find('.AttList').attr('Std_Id');
Assuming that this is the div or the parent of that div

Categories