This is my code:
$.get("http://www.roblox.com/catalog/", function(onWebsite) {
console.log($(onWebsite).find('.name.notranslate')[0].attr("href"));
});
Whenever I run it, it does not log anything to the console, all it says is: "Object {readyState: 1}". However, if I remove the .attr("href"), it works. Is there something wrong with my syntax?
Since .attr() is a jQuery function you need to use it with jQuery object.
Use
$(onWebsite).find('.name.notranslate').attr("href")
As per your current code $(onWebsite).find('.name.notranslate')[0] will return you underlying DOM element which doesn't have .attr() method.
You can use href property or Element.getAttribute() method
$(onWebsite).find('.name.notranslate')[0].href
OR
$(onWebsite).find('.name.notranslate')[0].getAttribute('href')
Maybe try:
$.get("http://www.roblox.com/catalog/", function(onWebsite) {
console.log(onWebsite.find('.name.notranslate')[0].attr("href"));
});
onWebsite must not be wrapped with the jQuery selector as its a return from a function.
Lets try this approach:
var a;
$.get("http://www.roblox.com/catalog/", function(onWebsite) {
a = $(onWebsite).find('.name.notranslate')[0];
console.log(a);
});
You will get
<a class="name notranslate" href="/Headless-Horseman-item?id=134082613" title="Headless Horseman">Headless Horseman</a>
So var a is the HTML Tag with href attribute. HTML tags doesn't have jQuery methods - only jQuery objects selected from DOM or "wrapped/selected HTML"
Here you can:
reference .href to get href
wrap a in jQuery to get: $(a).attr('href')
So end code would be (variant 1 is better):
var a;
$.get("http://www.roblox.com/catalog/", function(onWebsite) {
a = $(onWebsite).find('.name.notranslate')[0].href
console.log(a);
});
or without creation of temp variable
$.get("http://www.roblox.com/catalog/", function(onWebsite) {
console.log($(onWebsite).find('.name.notranslate')[0].href);
});
Related
I'm going through some legacy code on a submission form and replacing JQuery w/ vanilla JS.
Right now, I have this function that uses .val() (JQuery) to grab the value for an undefined input:
myFunction: function(){
var subscription = $('input[name="subscription_id"]').val();
// Do something with subscription
}
When I run the code in my browser, I get no issues - the code is meant to work only if a subscription is passed into the input - if it's not there, we just get an undefined value. The value returned by the JQuery combo of $() and .val() console logs to 'undefined'.
When I replace the JQuery with vanilla JS, like so:
myFunction: function(){
var subscription = document.querySelector('input[name="subscription_id"]').value;
// Do something with subscription
}
And then try to run my form, I get the following error in the console:
Uncaught TypeError: Cannot read property 'value' of null
Why is this happening? And is there a workaround for this? Any help is appreciated. Thanks in advance.
This happens because
document.querySelector('input[name="subscription_id"]')
does not exist. For vanilla js, you need to check if it exists first, then get the value if it does. jQuery has a silent fail for this.
var element = document.querySelector('input[name="subscription_id"]');
// If it exists, return its value, or null
var subscription = element ? element.value : null;
Just use a condition:
var elem = document.querySelector('input[name="subscription_id"]');
var subscription = elem ? elem.value : "";
I have created the following function.
function showAllSelectOpts(select)
{
selectLength = select.children().length;
select.attr('size',selectLength);
select.css('height','auto');
select.focusout(function(){
select.attr('size','1');
});
}
When it is called directly on a select element like this showAllSelectOpts(mySelect); it works fine, but when called within another function, as below using the keyword "this", it returns the error. Type error: select.children not a function
$('select').on('focus',function(){
showAllSelectOpts(this);
})
Is this a scope issue or what, and how can I resolve it?
In an event handler, this is a reference to the DOM element, not a jQuery object. But your showAllSelectOpts expects its argument to be a jQuery object.
Either change the call to wrap the DOM element with $():
showAllSelectOpts($(this));
...or update showAllSelectOpts to do so itself:
function showAllSelectOpts(select)
{
select = $(select); // ***
selectLength = select.children().length;
select.attr('size',selectLength);
select.css('height','auto');
select.focusout(function(){
select.attr('size','1');
});
}
Side note: As A.Wolff points out, your function attaches a new focusout handler to the select every time it's called. You only want one.
I'd remove that part of the handler entirely, and replace it with a single focusout:
function showAllSelectOpts(select)
{
var selectLength = select.children().length;
select.attr('size',selectLength);
select.css('height','auto');
}
$('select')
.on('focus',function(){
showAllSelectOpts($(this));
})
.on('focusout', function(){
$(this).attr('size', '1');
});
Also note that I added a var for selectLength in showAllSelectOpts (although actually, you could just remove the variable entirely); without one, the code is falling prey to The Horror of Implicit Globals (that's a post on my anemic little blog). Be sure to declare your variables.
jQuery event listener callbacks set this as the HTMLElement that the event was fired on.
In your callback you are expecting a jQuery object, but you have the HTMLElement.
You can pass the HTMLElement to a jQuery constructor and pass it into the showAllSelectOpts function
$('select').on('focus',function(){
showAllSelectOpts($(this));
})
Try this one -
$('select').on('focus',function() {
showAllSelectOpts($(this)); })
Try this:
var myselect = $('select');
$('select').on('focus',function(){
showAllSelectOpts(myselect);
})
A better way could be:
$('select').on('focus',function(event){
showAllSelectOpts($(event.target));
})
Why your code not working?
$('select').on('focus',function(){
//Here `this` is bound with the dom html element, not the $('select') object.
showAllSelectOpts(this);
})
These previous answers fix it. I'd just add here to create it as an extension since $(this) refers to a prototype of one method call.
$.fn.showAllSelectOpts=function() {
$(this).on('focus',()=>{
$(this)
.css('height','auto')
.attr('size',$(this).children().length)
.focusout(()=>{
$(this).attr('size','1');
});
});
};
$('select').showAllSelectOpts();
i get error TypeError: $(...) is null.
<script>
$('w_pages').observe('change', function(){
parent.preview.location = 'W/preview/<?=$page['parent_id'] ?>/?p='+$('w_pages').value;
});
$('w_layout').observe('click', function(){
parent.preview.Tiny.showURL('S/layout/'+$('w_pages').value+'?ajax=true',true)
});
</script>
i read that it is because of a conflict. how do i wrap this in noConflict()
There is no conflict here.
You are using the dollar function of Prototype, which returns a reference to the element with id equal to its argument. If no such element exists in the page it returns null, which in turn causes the TypeError.
I don't know why no such element exists in your page or how to make the JS work like it should, but you can avoid the immediate error by checking the return value before calling methods on it:
var wPages = $('w_pages');
if (wPages) {
wPages.observe('change', function(){
parent.preview.location =
'W/preview/<?=$page['parent_id'] ?>/?p='+wPages.value;
});
}
// The same for w_layout
i fixed it. i was indeed missing the element. thanx for putting me in the right direction.
I'm teaching myself AJAX to AJAXify my site. In my template, I have the following JS code to get some JSON data from a view then append the data to a div.
function filter(type) {
$.getJSON(
'/activity_stream/global-activity-stream/',
{xhr: "true", filter: type},
function(data) {
$('.mainContent').children().remove();
$(data).appendTo('.mainContent');
});
}
$(".btn").click(function () {
filter("recent");
});
}
I think my view is returning proper JSON but now data is not being added to the .mainContent div.
It gives this error:
Uncaught TypeError: Cannot read property 'ownerDocument' of undefined.
Make sure you're passing a selector to jQuery, not some form of data:
$( '.my-selector' )
not:
$( [ 'my-data' ] )
I had a similar issue.
I was using jQuery.map but I forgot to use jQuery.map(...).get() at the end to work with a normal array.
The same issue came up for me inside of $elms.each().
Because:
the function you pass to .each(Function) exposes (at least) two arguments; the first being the index and the second being the element in the current element in the list, and
because other similar looping methods give current the element in the array before the index
you may be tempted to do this:
$elms.each((item) => $(item).addClass('wrong'));
When this is what you need:
$elms.each((index, item) => $(item).addClass('wrong'));
In case you are appending to the DOM, make sure the content is compatible:
modal.find ('div.modal-body').append (content) // check content
If you use ES6 anon functions, it will conflict with $(this)
This works:
$('.dna-list').on('click', '.card', function(e) {
console.log($(this));
});
This doesn't work:
$('.dna-list').on('click', '.card', (e) => {
console.log($(this));
});
In my case, this error happened because my HTML had a trailing linebreak.
var myHtml = '<p>\
This should work.\
But does not.\
</p>\
';
jQuery('.something').append(myHtml); // this causes the error
To avoid the error, you just need to trim the HTML.
jQuery('.something').append(jQuery.trim(myHtml)); // this works
I am trying to check if an object with class sourceFocus has data in it. However when I check it, it does not have data when it should. What am I doing wrong here?
$('.source').click(function() {
$('.source').removeClass('sourceFocus');
$(this).addClass('sourceFocus');
$(this).data('source_selected', true);
console.log($.hasData(this));
console.log(this);
});
$('.target').click(function() {
$('.target').removeClass('targetFocus');
$(this).addClass('targetFocus');
$(this).data('target_used', true);
//$('.sourceFocus').data('source_used', true);
console.log($.hasData('.sourceFocus'));
if($.hasData('.sourceFocus')){
console.log("has data worked");
check_for_duplicates();
}
I don't think the .hasData() method accepts selectors in your case .sourceFocus, try selecting .sourcefocus as an element and then passing that to the .hasData() function.
try something like...
console.log($.hasData($('.sourceFocus:first')));
$.hasData() checks against a DOM Element
you have to get it out of the jQuery object, either using array notation or the .get() method (not to be confused with the $.get() ajax method)
console.log($.hasData($('.sourceFocus')[0]));
If you trying to read the HTML between the tags for which you are using .sourceFocus class then do this in your if statement:
$.hasData($('.sourceFocus').html())