Editing objects in jQuery - javascript

$(function(){
var z = document.body.children[0];
var x=$("li", z);
x.name="Johnny";
alert(x.prop(name));
});
x should be an object containing all the elements within the first ul in the body.
Regardless of what the object contains, I would like to add a property with a value, and then use the prop() method to show it - but that doesn't seem to work. Why is that?
I saw a script containing the following: var $x = $("div"); - Do I have to add $ to the variable name if it's a jQuery object?

To select the first ul element inside a page you can do:
$("ul:first li")
This way you are going to select all lines inside the first list in the page.
To store arbitrary data in an element you can use the method data, like this:
$("element").data('key', 'value');
and to retrieve the data:
$("element").data('key');
More info, for the data method.
If you really want to add an attribute you can use the attr method, it works the same way as the data method, but it would reflect in the DOM.

If you want all li elements in the first ul element, then this should do the trick:
var elements = $("ul:eq(0) li");
Here is a very simple example of this in action.
In regards to setting a property, you can do element.name = "test" and it will work ok. But what you need to understand is that this is setting a name property on the jquery collection object and NOT on any of the actual elements.
What you can do however, is set the property like so:
elements.prop("name", "test");
and the access it like so:
var name = elements.prop("name");//name will be "test"
Here is a working example
As I mentioned in my comment, you don't need to prefix the variable with $. But this can be helpful to easily see which variables are JQuery objects.

Number 1. x is a jQuery object, you added to that instance a name property, then you're using name though it wasn't defined.
If you want to change a property of the element you got with jQuery the ways are:
$('selector').prop('property', 'value');
$('selector').attr('attribute', 'value');
$('selector').get(index).property = "value";
Number 2. no you don't have to, $ prefix is simply a convention to make the code more readable.
Is there any specific reason behind using $ with variable in jQuery

Using the selector from #musefan answer, you can take the collection returned, and use the attr() method to add an attribute and value to each item selected. However, I've modified his selector slightly to actually grab "all" elements in there, (just in case future visitors wonder)
var elements = $("ul:eq(0)").children();
elements.attr("attrName", value);
So if you wanted to set the title:
var elements = $("ul:eq(0)").children();
elements.attr("title", "Johnny");
You probably don't want to alert these values, browsers may ask you to stop allowing alerts on the page... but if you really did, then you could throw in an .each() after that.
var elements = $("ul:eq(0)").children();
elements.attr("title", "Johnny").each(function(){
alert($(this).attr("title");
});

Related

Trying to remove an element with data-value equal to a previously created variable?

When I click on a "trash" button I want to delete the message block. There are multiple message blocks but they all have unique data-values. The id of the targeted block I want to delete is stored in the data-value of .send-message-button.
I tried making a variable that I could pass onto the targeted .messageblock element. I checked with an alert to see if the variable gets the proper number, which it does. However when I alert the whole thing, it gives [object object] (without the .remove, of course).
How can I do this?
var trashid = $(".send-message-button").attr("data-value");
$('.message-block').attr("data-value", trashid).remove();
If you want to retrieve an element using the value of one of its attributes you need to use the attribute selector, not the setter of the attr() method.
There's two main ways to do this. Firstly if the data attribute is present in the DOM then you can use an attribute selector:
var trashid = $(".send-message-button").data('value');
$('.message-block[data-value="' + trashid + '"]').remove();
Alternatively if the data attribute is held in jQuery's cache (as will be the case if you use data() as a getter/setter, as you should be) then you can use filter() instead:
var trashid = $(".send-message-button").data('value');
$('.message-block').filter((i, e) => $(e).data('value') === trashid).remove();

How to setAttribute in cell td HTML?

this is my script but it doesn't work:
var first = document.getElementById("sheet").rows[0];
var two = first.cells(4);
two.setAttribute('style','display:none');
Note that cells isn't a function or method, it's a property that returns an HTML collection that can be accessed by index:
var two = first.cells[4];
Rather than using setAttribute, just set the property directly:
two.style.display = 'none';
I dont know if youre really trying to set attribute OR add function onBlur - I will answer both
If you want to set an ATTRIBUTE:
Then your approach is actually right - considering two is a HTMLObject
two.setAttribute("class","unchecked"); //this sets class .unchecked to the "two"
This replaces all existing classes with the new class, fine if you only ever use just 1 class.
Historically you'd have work your own class merging, but for modern browsers, there is much more convenient way: two.classList.add("unchecked"); which adds to existing class list instead of replacing it, but only if the class is not there yet :-)
If you want to add a FUNCTION() which would fire onBlur
Then you have to use something to bind - the easiest way is to add a function inside an HTMLObject attribute(property) - notice! HTMLObject attribute (property) IS NOT the same as attribute you see inside your html code:
two.onblur=function(){ /*SomeJavaScriptCode*/ };
or if you already have a function:
two.onblur = cekUndo;
NOTICE! there are no () brackets - the onblur will run the function when its needed you dont want the function to fire immediatly...
I recommend you also to check a .addEventListener method - it is more adjustable and you can add e.g. more functions on one event
Note: You can do <td onblur="myFunction()"> - add it directly to HTML, but I dont think you can do that on the run like this you have to bind :) ...
EDIT: as to your second problem - as RobG said, you have to access the cells collection with [] brackets:
var two = first.cells[4];
Also check if you are actually have a cell of that index (cells are indexed from 0 to X => index 4 means 5th )

Javascript - extract object ID from a Javascript object

So I am not sure if my title is clear enough. I essentially have a div saved as a Javascript object which looks like this: [div#field_30.checkbox_group]
The field_30 is the ID which I am trying to extract here. doing something like object.id is not working. Does anyone know how to get the ID?
Note: I saved the object like this: var object = $(".workspace .selected"); which grabs the currently selected div inside the object called workspace. Sorry is this is a rookie mistake, I just can't seem to find anything anywhere. Thanks for the help...
var object = $(".workspace .selected"); will return a jQuery wrapped element that has jQuery properties and methods rather than element properties and methods. This means that any of
object[0].id
object.prop("id")
object.attr("id")
should work, but the 1st option should be the best performance-wise. It gets the id property of the the 1st element contained by the jQuery object, which is your div.
Your object is in fact a jQuery object, not a dom object.
To use the dom object use,
object[0].id
Or using, jquery, (Since it is already there)
object.prop('id');
You can use either $jquery_object.attr('id') or $jquery_object.eq(0).id
See this for exemple: http://jsfiddle.net/cquuT/
In this case it looks like object is the result of a jQuery select. To get to the actual DOM object you need to use [0]. Then you can access the id property
object[0].id
I don't see a complete answer here, so I'll provide my own.
If you're using jQuery selector $(), then you'll get jQuery-wrapped collection, not a single element.
(I assume now that you're using jQuery 1.5.2, the same as StackOverflow uses now.)
Universal solution to get ids of all elements returned by selector is:
.map(function(){ return this.id; })
Running $(".post-text").map(function(){ return this.id; }) on current page will return something like: ["", "", "", "", ""]
To get id of the first element returned by selector use:
.attr('id')
Running $("div").attr('id') on current page will return "notify-container".
Since jQuery 1.6 you can also use .prop('id') here.
If you know, that query will return only one element or you just want the first element matching given selector, then use .attr which is obviously a simpler solution.

Jquery - Reference by ID - Supposed to return an array?

I just started using jQuery, and various sources suggest that the following should be used to reference an element by ID:
$("#imgThumbnail")
theoretically making something like this possible:
$("#imgThumbnail").src;
But my testing indicates that something like $("#imgThumbnail") returns an array, making the following necessary:
$("#imgThumbnail")[0].src;
Do I really need to reference by the index of the array every time I am trying to reference something by ID (i.e., var oObj = $("#someobjectid")[0]; )?
You should get the src attribute to get the value
$("#imgThumbnail").attr('src');
This post explains what the $ function returns and various ways to use it.
$(selector)
Returns a jQuery object, which could contain a number of DOM elements.
$(selector)[0] or $(selector).get(0)
Returns the first result as an actual DOM element.
$(selector).eq(0) or $($(selector).get(0))
Returns the DOM element wrapped in a jQuery object so that we can do stuff like:
$(selector).eq(0).addClass("deleted").fadeOut();
$(specifier) will return a collection, so yes if you want to call something on an individual member you need to pick which one. In most cases though there is a collection operator you can use to achieve the same result. For instance, you could call $('#imgThumbnail').attr('src', 'value')
You should bear in mind that it's not really an array, it's a jQuery object which, among other things, allows array-style access
$(whatever)
returns the jQuery object. On the jQuery object you can do jQuery and jQuery plugin things, eg. .text() to return the text inside the element or .css("background", "pink") to make the element(s) pink.
Since src isn't a jQuery thing you cannot access it. src is however both a HTML attribute, and you can access those with the attr method:
.attr("src")` and `.attr("src", "http://www.example.com/myimage.png")
src is also a DOM-property and you can access DOM-properties using [index] or by iterating through the jQuery object with each:
.each(function(){
this.src = "http://www.example.com/myimage.png";
})
I don't think you should be using .src with jQuery.
Try $("#imgThumbnail").attr('src');
(this will read the src attribute, you set it with a second arg if you like)
See here:
http://docs.jquery.com/Attributes/attr
to set the src attribute use
$("#imgThumbnail").attr("src", value)
if you use something like a class selector or tag like so
$("img").attr("src", value)
It will modify all the image src attributes on the page. Hence the $ function returns an array.
And you do not need to reference it specifically.

How to get ID when you pass my ID

I have a function that gets passed the document object like:
toggle( $('username') );
function Toggle(id)
{
/// ??
}
How can I get the actual name of the object passed i.e. username?
If I understand you correctly, can't you:
$(id).attr("id");
or
$(id).attr("name");
Or am I mistaken?
Either what Jonathon said or with
$(id).val();
The object that gets passed in is an instance of the jQuery object, which contains a set of elements (in this case with only one element in it). The documentation is on the jQuery documentation site.
The jQuery object that $() returns, wraps one or more DOM elements.
Using the accessors $().attr(), $().val(), $().text() and $().html() will act on the first of those wrapped elements.
If you want to drop out of jQuery mode so that you can work with the native DOM element (sometimes useful) use $().get( index ).
eg
var el = $('#mytextbox').get(0);
el.value = 'a new value';
alert(el.id);
etc...

Categories