I have multiple objects with the classname "level1" (this is built on asp.net, the element does not allow setting an ID here)
What I am trying to do is get one of them and assign css properties
$(".level1")[1].css({"background-color":"yellow"});
I get the error
Error: Object doesn't support property or method 'css'
When I do this:
console.log($(".level1")[1].innerHTML);
I get the correct innerHTML, so I know it gets the right element
Use eq:
$(".level1").eq(1).css({
"background-color": "yellow"
});
$(".level1")[1] returns the HTML and not the jQuery Object, so you cannot call jQuery method on it. Use eq instead.
eq(1) will get the Second element having class level1(Index starts from 0)
Docs: http://api.jquery.com/eq/
Reduce the set of matched elements to the one at the specified index.
$(selector)[1] gets the DOM element. To manipulate it again you need the jQuery object:
$($('.level1')[1]).css('background-color', 'yellow');
Edit - see Tushar's answer using .eq()
Make from $(".level1")[1] a jQuery object, because [1] returns HTML DOM element and you need jQuery object for .css() method.
$($(".level1")[1]).css({
"background-color":"yellow"
});
Related
I am working on a project and not allowed to use jQuery. I am looking for equivalent plain Javascript code for below jquery:
$('img[alt="Apple Store Logo"]').parent().removeAttr("target");
I found below information :
jQuery Javascript
parent() : .parentElement
removeAttr() : removeAttribute()
Couldn't find how to construct above selector.
You can use querySelectorAll() to get NodeList that match the specified selector. Then implement forEach() to iterate over all the elements to remove the attribute from the element's parent node with
parentNode and removeAttribute().
Try the following:
document.querySelectorAll('img[alt="Apple Store Logo"]').forEach(function(el){
el.parentNode.removeAttribute("target");
});
Some older browser does not supprot forEach() on a NodeList . Use Array.prototype.slice.call() in that situation to implement forEach():
var images = Array.prototype.slice.call(document.querySelectorAll(selector));
images.forEach(function(el){
el.parentNode.removeAttribute("target");
});
The first part of your call is a simple DOM query retrieving all <img> elements with an alt attribute matching "Apple Store Logo".
$('img[alt="Apple Store Logo"]')
This can be done in vanilla JS easily enough:
document.querySelectorAll('img[alt="Apple Store Logo"]')
However,document.querySelectorAll returns a NodeList, not an Array. We can convert the NodeList to an Array by calling Array.prototype.slice on it:
Array.prototype.slice.call(document.querySelectorAll('img[alt="Apple Store Logo"]'))
My knowledge of jQuery is poor, but I believe the remaining methods are called iteratively against the elements returned in the query result. Therefore, assuming the intent is to get a reference to the img element's parent element, and remove its target attribute, the whole code block could be translated to:
Array.prototype.slice.call(document.querySelectorAll('img[alt="Apple Store Logo"]')).forEach(function (img) {
img.parentNode.removeAttribute('target');
});
Using jQuery 3.1.1, why are the results of these two different?
$('dd[data-something]').first().innerText;
^ returns undefined
$('dd[data-something]')[0].innerText;
^ returns valid data
Wouldn't the 0th element of an array also be the .first() element?
Edit: Thanks all, I got it, jQuery object versus DOM element. As the debugger clearly showed before I could delete this :) That's a clear sign its time to call it quits for the day.
Because first returns a jQuery object wrapped around the first raw DOM element in the set (which has no innerText property, but does have that handy text method), and [0] directly accesses that raw DOM element (which does have an innerText property on most browsers).
first() will return a jQuery object which is different from the normal JavaScript object and won't work with native JavaScript APIs, here's a qoute from the official documentation
the .first() method constructs a new jQuery object from the first element in that set.
The second one (index zero) will return a JavaScript object it's almost like calling the element using querySelectorAll()
So if you want to get the text use text() from jQuery and it will work
$('dd[data-something]').first().text('new text'); // this will change the text
can you help me understand why this is not working?
var elementTab1 = $('#tab1 .item-media.modificato');
elementTab1[0].addClass('selezionato');
this through this error
TypeError: undefined is not a function (evaluating 'elementTab1[0].addClass('selezionato')')
Thanks
elementTab1 is already a jQuery object. It contains an array of matched elements in the DOM. Accessing the first index using [0] will return a native element with access to the native JavaScript API (and not jQuery's).
jQuery does provide a nice way to grab items from the array though. It is .eq().
elementTab1.eq(0).addClass('selezionato');
Accessing an element of a JQuery object (via your elementTab1[0]) call returns the DOM element, not a JQuery element.
DOM elements do not have an .addClass method.
The following code should work for you:
$(elementTab1[0]).addClass(".selezionato");
Alternately, just skip JQuery and use the native DOM APIs:
document
.querySelector("#tab1 .item-media.modificato")
.classList
.add(".selezionato");
A <img /> element has a data-id attribute that I want to retrieve using jQuery. I believe the .data() function can do this.
$('.photo').get(0).data('id')
Problem: When I tried using .data('id') to retrieve the attribute, I get the error:
Uncaught TypeError: Object #<HTMLImageElement> has no method 'data'
Where did I go wrong?
jsfiddle: http://jsfiddle.net/KLG3R/
like others said, your problem is the .get(0) which returns the HTML element itself, rather than a jquery object. To get a certain element, you use the :eq pseudo selector like:
http://jsfiddle.net/gunderson/KLG3R/2/
$('#result').html( $('.photo:eq(0)').data('id') );
You need to use data to a jquery object and get(0) will return the element.
$('#result').html( $('.photo').data('id') );
Check the below fiddle
http://jsfiddle.net/KLG3R/1/
$('.photo').get(0) will return the HTMLImageElement, not the jQuery object, so it doesn't have a method .data.
You should just do with: $('.photo').data('id')
use .attr() function. Like
$('#result').html( $('.photo').attr('data-id') );
Your using jQuery .get() you need to use .eq() in this case. Also your using .data() which is used to store data on the dom. You need to be using .attr() which gives you access to the attributes of the element.
$(function () {
var photos = $('.photo');
$('#result').html(photos.eq(0).attr('data-id'));
});
This should be working for you now: http://jsfiddle.net/KLG3R/4/
There are two types of an element. That is DOM object and jQuery object;
jQuery object has data() method, while DOM object like your xx..get(0) has no method data();
So, if you want to use data() method, you must ensure the object is jQuery object.
I'm just starting with JQuery and am working through a tutorial vid. At one point the presenters go for javascript instead of a JQuery selector. Just wondering why the javascript getElementById below works fine when passing an object to a function, but the second one doesn't?
Thanks!
// works
addTask(document.getElementById('taskText'), evt);
// doesn't
addTask($('#taskText'), evt);
getElementById() returns a DOM element reference.
jQuery's selector returns a jQuery object. You can get the element reference from the jQuery object using
$('#taskText').get(0);
See http://api.jquery.com/get/
To add to the other answer, regarding the result, if you want to use jQuery (which is easier to read), you can get the dom node directly like so:
addTask($('#taskText')[0], evt);
$('#taskText') returns a jQuery object reference.
document.getElementById('taskText') returns a DOM element reference.
If your addTask() function doesn't know how to convert them to what it needs, then that would be the issue since one of them will need a conversion.
If you want to get the first DOM element reference from the jQuery object, you can do so with this:
$('#taskText').get(0)
So these two should be identical:
$('#taskText').get(0)
document.getElementById('taskText')
Both are not exactly same
document.getElementById('taskText'); //returns a HTML DOM Object
var contents = $('#taskText'); //returns a jQuery Object
var contents = $('#taskText')[0]; //returns a HTML DOM Object
so you have to change it to get HTML Dom Object
addTask($('#taskText')[0], evt);
As #Phil and #jfriend00 have pointed out, document.getElementById('taskText') is a DOM element, and $('#taskText') is a jQuery object. The latter is an object of all DOM elements that match the selector.
Think of it as a zero based array, you could pass in the DOM element by doing this:
addTask($('#taskText')[0], evt);