getElementById returns null? (with Vue) - javascript

So I tried to find the answer, but no success.
window.onload = function() {
console.log(document.getElementById('#sell'));
if(document.getElementById('#sell')){
alert('jo');
//Init for Vue
}
}
It works with jQuery but not with vanilla JS why?
console.log(document.getElementById('#sell'));
Result returns NULL.
jQuery example:
if ( $( "#sell" ).length ) {
const app = new Vue({
el: '#sell',
components: { sellPicture }
});
}
In my sell.blade.php it looks like that
...
<div id="sell">
<sell-picture></sell-picture>
</div>
....
My script is added before /body
Just a side question. I need jQuery for Bootstrap, is it bad to use it also in Vue if I don't change the DOM with it?

Remove # from the id param like below
window.onload = function() {
console.log(document.getElementById('sell'));
if(document.getElementById('sell')){
alert('jo');
//Init for Vue
}
}

document.getElementById('#sell') does not require a # to identify Ids. That is the syntax you would use in a jQuery selector, but a DOM selector will literally take the string and match it against the ID attribute value. The same goes for document.getElementByClassName(), where you would not need a . to identify the class.
The Mozilla MDN documentation gives an example of this here.
This should work:
window.onload = function() {
console.log(document.getElementById('sell'));
if(document.getElementById('sell')){
alert('jo');
//Init for Vue
}
}

Please try to use
$(document).ready(function(){ console.log($("#sell")); });

Related

Materialize getInstance(elem) inside AngularJS component's controller

I'm trying to use the .open() method of materialize to open a modal component within AngularJS on the page load.
So my component file (loginModal.js) has the following code:
angular.module('my-app').component('loginModal', {
templateUrl:'app/components/templates/loginModal.html',
controller: loginModalController
})
function loginModalController()
{
angular.element(document).ready( function(){
var loginModal = document.querySelectorAll('.modal');
var loginModal_options = {};
var loginModal_instance = M.Modal.init( loginModal, loginModal_options);
console.log(loginModal_instance);
loginModal_instance.open();
var instance = M.Modal.getInstance(loginModal);
instance.open();
});
}
While the initialization is happening as expected when I'm trying to trigger the open method, through the loginModal_instance variable I'm getting
loginModal_instance.open is not a function
while through instance variable I'm getting
Cannot read property 'open' of undefined
Instead, If I'm going to use JQuery, its working
function loginModalController()
{
$(document).ready(function(){
$('.modal').modal();
$('#login-modal').modal('open');
});
}
Any ideas? Am I doing anything wrong?
Actually by using querySelector() instead of querySelectorAll() did the trick.

Jquery version of yui .getElementsBy

I am trying to update from YUI to jQuery for a web app; however, I am new to working in jQuery. I have this code block in YUI:
function getChildUL(childEl){
var childrenUL = YAHOO.util.Dom.getElementsBy(
function(element) {
return element.parentNode == childEl;
}, "UL", childEl);
childrenUL = childrenUL[childrenUL.length-1];
return childrenUL;
}
I had found this Link, and tried rewriting the block in jQuery based on the accepted answer. I am getting undefined for childrenUL. This is my attempt:
function getChildUL(childEl){
var childrenUL = $("UL").filter(function(element) {
return element.parentNode == childEl;
}).get();
childrenUL = childrenUL[childrenUL.length-1];
return childrenUL;
}
Thank you for any assistance.
You have an error in your code: parentNode isn't a jQuery function. I think you should use parent() or closest() function.

How can I retrieve the target element that a jquery plugin is attached to?

I am new to writing JQuery Plugins...and have a question regarding returning the selector used to bind the plugin to.
Lets say we attach a jQuery plugin to an element like this...
$(".someClass").viEdit();
And this is the Plugin ...
(function ($) {
$.fn.viEdit = function () {
var myTarget = "????"; // See Below
};
}(jQuery));
Now...How can I retrieve the target that was used to bind the jQuery?
I don't mean $(this), I'm looking for .someClass in this case.
As a second example, if it was set like this...
$("#myElement").viEdit();
I would be looking for...
#myElement
Any help would be greatly appreciated!
You can use this.selector:
http://jsfiddle.net/3NAwD/
(function ($) {
$.fn.viEdit = function () {
console.log(this.selector);
};
}(jQuery));
Note that something like $(document.getElementById('someId')).viEdit(); will give you a blank selector.
There were a .selector property, which is deprecated in newer versions.
The advised method now is to pass it as a option like
(function ($) {
$.fn.viEdit = function (options) {
var myTarget = options.target;
};
}(jQuery));
$("#myElement").viEdit({
target: '#myElement'
});

Unexpected jQuery syntax error by chaining a plug-in after .find()

I've baked a plug-in to handle runtime searches on input fields I'm using all over a big site.The plug-in works perfect in every situation but this http://jsfiddle.net/tonino/v8d2A/
$(document).ready(function () {
var callback_methods = { /* methods here */ };
var input_html = '<div class="search"><input name="search-field" value="Search..."></div>';
$(document).on('click', 'div.add', function (event) {
if (!$('li div.add + div').hasClass('search')) {
var input = $(this).after(input_html).parent().find('input');
input.focus();
input.hunter({url:'<?php echo $this->request->base; ?>/searches', callback:callback_methods, var_name:'data[Search][term]'});
// other code after
}
});
});​
If I comment the hunter plug-in everything works fine.
I'm sure is some concept on how it must be structured, here is the code: jquery.hunter.1.3.js
Why my plug-in make this error in this situation, where I'm wrong on writing it?
the problem is this part of your code:
var selector = this.selector;
var def_css = {backgroundPosition:'-16px center', paddingLeft:$(selector).css('padding-left')}
if (settings.loader) { setStyle(def_css); }
var selector = this.selector;
and later:
$(this.selector).blur(function () {
first of all your code wont work when the if-condition is fulfilled, because you are trying to redeclare the variable 'selector' inside the if block. just leave the var-statement out there:
if (settings.loader) { setStyle(def_css); }
selector = this.selector;
but YOUR MAIN-problem is that 'this.selector' contains '.parent() input' which i doubt is a valid jQuery selector.
why are you doing that? why dont you just use $(this) save it into a variable and use this???
eg:
// first line in your plugin
$this = $(this)
// later you could use the $this var
$this.blur(function () {
To get rid of the error change this line:
var input = $(this).after(input_html).parent().find('input');
To the following:
var input = $(input_html).insertAfter($(this));
The core problem though is that the jquery.hunter plugin is using the this.selector variable for some reason - you don't need this - the plugin should use $(this) instead of $(this.selector)

Refer to immediate selector object with jQuery?

I'm trying to learn some jQuery, and I setup a test page with the following code:
<a id='encode' href='javascript: void(0)'>encode</a> |
<a id='decode' href='javascript: void(0)'>decode</a> |
<br/>
<textarea id='randomString' cols='100' rows='5'></textarea>
<script type='text/javascript'>
$(document.ready(function () {
$('#encode').click(function() {
$('#randomString').val(escape($('#randomString').val()));
});
$('#decode').click(function() {
$('#randomString').val(unescape($('#randomString').val()));
});
});
</script>
The idea is I can put something in the textarea and click either "encode" or "decode", and it will either escape or unescape what I put into the textarea.
This code works just fine, but my question has to do with how I am changing the value of the textarea. In my code, I am selecting the textarea value twice: once to (un)escape it, and once again to change the value. IMO this seems clunky and maybe unnecessary. I thought maybe I could do something like this instead:
$('#randomString').val(escape(this));
But this seems to refer to the object of the link I clicked, not the #randomString selector, so is there some other magic word I can use to reference that $('#randomString')?
$('#randomString').val(escape(this));
This does not get the object you want. It is effectively the equivalent of doing this:
var foo = escape(this);
$('#randomString').val(foo);
this only means something different when you start a new scope with a function definition.
jQuery does offer this kind of functionality with a callback option:
$('#randomString').val(function (idx, oldVal) {
return escape(oldVal);
});
The second parameter is the current value of the element; the return value sets a new value for the element.
You can try this
$(document.ready(function () {
$('#encode').click(function() {
var $randomString = $('#randomString');
$randomString.val(escape($randomString.val()));
});
$('#decode').click(function() {
var $randomString = $('#randomString');
$randomString.val(unescape($randomString.val()));
});
});
The short answer, if I understand you correctly, is no. There isn't a way to refer to $('#randomString') where you're talking about. It's just a parameter to the val method, so it's just plain JavaScript syntax, no jQuery "magic".
To accomplish the task at hand and make the code cleaner and less clunky, I would save off the jQuery object for #randomString so you don't have to keep creating it:
$(document.ready(function () {
var $rndStr = $('#randomString');
$('#encode').click(function() {
$rndStr.val(escape($rndStr.val()));
});
$('#decode').click(function() {
$('#rndStr').val(unescape($rndStr.val()));
});
});
You could make it a little generic:
$.fn.applyVal = function(func) {
return this.each(function() {
$(this).val( func( $(this).val() ) );
});
};
Then the following call is enough:
$('#randomString').applyVal(escape);

Categories

Resources