I am creating a variable that stores an elements ID in the variable. I could write it like this:
var webappData = document.getElementById('web-app-data');
If I wanted to do the same using jQuery I think I would write it like this:
var webappData = $('#web-app-data');
However, when I try that it doesn't work. (Script throws an error because the variable isn't selecting the div with that Id.)
How would I use jQuery to select an element and store it in a variable?
document.getElementById('web-app-data') isn't the same as $('#web-app-data'). The later returns jQuery object, which is kind of an array of HTMLElement objects (only one in your case).
If you want to get HTMLElement, use $('#web-app-data')[0]. Check:
document.getElementById('web-app-data') === $('#web-app-data')[0]; // true
It's ok.. Maybe something else is wrong in your code..
Example:
<div id="web-app-data">
Hello
</div>
<script type='text/javascript'>
var webappData = $('#web-app-data');
alert(webappData.text()); // Hello
</script>
Fiddle
Above code should work just fine. Your problem might be, that jQuery doesn't find any corresponding elements from the DOM since the element has been removed or hasn't been loaded there yet. If you try to
console.log($('#web-app-data'));
that variable, you can check if jQuery actually found anything. jQuery object should have lenght of (atleast) one if corrensponding element is indeed in DOM atm.
That will work and you use just like it was the full JQuery selector.
var elm = $('#webappData');
if (elm.hasClass('someClass')) elm.removeClass('someClass');
return;
Related
I have the following link inside my web page:
Attachments and Documents
Now I want to select this link based on its text "Attachments and Documents", and set a target attribute for it.
So I tried the following:
var tgb = $('a:contains("Attachments and Documents")')[0];
tgb.attr('target', '_blank');
But I got the following exception :
TypeError: tgb.attr is not a function
As soon as you use index ([0]), tab is no more a jQuery object. To get the jQuery function attr() you have to wrap tgb with $:
var tgb = $('a:contains("Attachments and Documents")')[0];
$(tgb).attr('target', '_blank');
// to demonstrate result
console.log(tgb)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Attachments and Documents
attr() is a jQuery function. You need to target your variable using jQuery methods
$(tgb)
Hope this helps :)
var tgb = $('a:contains("Attachments and Documents")')[0];
$(tgb).attr('target', '_blank');
console.log(tgb);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Attachments and Documents
var tgb = $('a:contains("Attachments and Documents")');
tgb.attr('target', '_blank');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Attachments and Documents
The issue with your logic was the [0] that you were putting on the tgb. [0] on a jQuery object breaks the element out of the jQuery object and returns the native Element. There are various reasons why you would want to do this, such as if you wanted to access element properties and you don't want to go through the jQuery prop() or attr() method.
However in your case, you are trying to use the attr() method off of tgb. However, attr() is a jQuery method. Since you broke the element out of the jQuery object, this will not work.
Rather than turning the tgb back into a jQuery object, simply take off the [0]. This fixes your issue, and removes the need to create another jQuery object which, give the snippet you provided, is unnecessary work.
Optionally, if you do want it to be a native Element you could just set the attribute directly.
var tgb = $(...)[0];
tgb.setAttribute('href', newValue);
//or
tgb.href = newValue;
When i check for the class name with .hasClass its not working.
function changeClass(){
var elBox = document.getElementById('box');
if(elBox.hasClass('blue')){
elBox.className = 'red';
}
}
var trigger = document.getElementById('trigger');
trigger.onmouseover = changeClass;
But generally its working when i check for attribute for example
if(elBox.hasAttribute('class') ....
I just don't get why the checking for class fails, maybe someone can help.
elBox is just a DOM object, wrap it with jQuery wrapper in order to use jQuery methods like .hasClass().
Instead of
if(elBox.hasClass('blue')){
Use
if($(elBox).hasClass('blue')){
elBox is a DOM element. You should use jQuery object for using jQuery method hasClass(). Try like following.
$('#box').hasClass('blue')
Or
$(elBox).hasClass('blue')
I wanted to put an id in my element's parent element. Below is my code:
<div>
<div id="child"></div>
<div>
Im aware that jquery has a way to select a parent element , but I dont know how what method shall I use to put an id to it. Below is my jquery code:
div_resizable = $( "#child" ).parent();
div_resizable.id = "div_resizable";
Above code doesnt work with me. It doesnt throw an error, but no changes had taken effect. Any solution to my problem?
For achieve what you want, you can use the jquery attr:
$("#child" ).parent().attr('id', 'newID');
Or you can use the prop:
$("#child" ).parent().prop('id', 'newID');
And you can check the difference between the two here: difference between prop() and attr()
Of course div_resizable.id = "div_resizable" doesn't work. div_resizeable is an jQuery array and you are trying to assign id to it.
Try .attr instead:
$("#child").parent().attr({id: "div_resizable"});
To set a property on the first element inside a jQuery result object:
div_resizable = $( "#child" ).parent()[0];
// ^^^
div_resizable.id = "div_resizable";
This picks the first Element from the result so that you can directly access the property.
Or:
$('#child').parent().prop('id', 'div_resizable');
Use the .prop() helper method to accomplish the same thing.
I have a set a dynamically created divs with the same class name. Now I want to append a entirely new div to all of the above mentioned divs.
Say the class name is extra-upper-block
At the end of my page I have this code
<script>
//function call to load dynamic content
</script>
<script>
$('.extra-upper-block').append('<div>New Div</div>');
</script>
This throws an error in chrome's console
Uncaught TypeError: undefined is not a function
But when this code is executed in chrome's console after the page is loaded, it works!
Why doesn't it work even when I load the dynamic content before executing the append command. Help?
Use jQuery class selector.
$(document).ready(function(){
$('.extra-upper-block').append('<div>New Div</div>');
});
Wrap your code in $(document).ready() for jQuery to get the elements available, and include jQuery file reference.
Note : .append() method is a part of jQuery.
Demo
document.getElementsByClassName returns an array-like object, you can't use it like jQuery, you need to access the individual element in a loop. Also, use appendChild on DOM elements, because they don't have an append method (like jQuery does).
Also, you are trying to append a string <div>New div</div>, you can't directly do that with a DOM element, so instead you can create the div element like so:
Demo
var elements = document.getElementsByClassName('extra-upper-block');
for(var i=0; i<elements.length; i++){
var newDiv = document.createElement('div');
newDiv.appendChild(document.createTextNode('New div'));
elements[i].appendChild(newDiv);
}
Note: querySelectorAll has better cross browser support than this. If you have jQuery included you can simply do:
$('extra-upper-block').append('<div>New Div</div>');
As you can see, with jQuery you can append a string directly.
try writing
document.getElementsByClassName('extra-upper-block')[0].appendChild(document.createElement('div'));
Append is a function in jQuery, try this:
<script>
$(function() {
$('.extra-upper-block').append('<div>New Div</div>');
});
</script>
Var divs = $(".txt"); this will return a list of divs with a class txt .
I want to add text to a selected div for example :
divs[4].html("Hello World"); this with return error saying divs[4].html is not a function. why ?
When you access a jQuery object by its DOM array index, you get the HTML element, not a jQuery object, which doesn't have the html() function. Use the eq(n) selector instead:
$(".txt:eq(4)").html("Hello World");
The divs[0] is giving you a DOM reference, not a jQuery object. So, pass that to the jQuery function ($() is shorthand for jQuery()):
$(document).ready(function(){
var divs = $('.txt');
$(divs[4]).html('this one');
});
http://jsfiddle.net/userdude/unu8g/
Note as well the use of $(document).ready(), which will wait until the DOM is accessible. $(window).load() will suffice for this as well, although it may fire after onDOMReady.
The non jQuery way:
document.getElementsByClassName("txt")[4].innerHTML = "banananana!";
Just a side note: I'd suggest learning basic browser javascript before moving to libraries.
It will give you an understanding of how such libraries work and will keep you from being 'locked in' to a specific few