return a single html element with jquery - javascript

How can I get jQuery to return a html element exactly the way that getElementById does?
if I console.log($('#container')) I will get :
[<div id="container"></div>]
But the API I am interacting with obviously doesn't want that (an array) - it wants :
<div id="container"></div>
I know I can achieve this with $('#container').get(0) and a few other ways, It just seems overkill - especially as I'm selecting an ID which will always be unique.
What am I missing guys?
Thanks

If you just want a single DOM element, then just use plain javascript:
var obj = document.getElementById("container");
jQuery selectors always create a jQuery object with an array of elements in it. That's just the way it's designed. If you want a single element, you either get the first element out of the jQuery object or you use a different tool.
From a jQuery object, you can get the first object either with:
$('#container').get(0)
or with:
$('#container')[0]
But, I would argue that both are more than you need if all you want is the single object that has an id. Just use document.getElementById(). If you want less typing, you could make your own short function:
function $$(id) {
return(document.getElementById(id));
}
var obj = $$("container");

try using .html() it will return the html of the element your selecting see:
http://api.jquery.com/html/

Related

Selecting the individuals from a group of jQuery elements

If I use jquery to select all my text inputs:
var inputs = $('#form input[type="text"]');
They are wrapped in jQuery. I can do whatever I want with them.
inputs.css('height', '1000px');
//muhahaha!
As a group they abide. But I seem to be missing something. I know I can see each one individually as if it was an array of objects.
console.log(inputs[0]);
// <input type="text" />
But the above output is just the html; when I do that it's no longer a jQuery object :(
inputs[0].css('font-size', '100px');
// Uncaught TypeError: Object #<HTMLInputElement> has no method 'css'
How do I continue to use jquery's methods on the individual without having to wrap each element again, or is this not possible for some strange, dark, inexplicable reason?
Didn't even know where to begin searching this one, and my jQuery journey has not lead me to the answer thus far. Thanks!
Have a look at this page: jQuery Filtering
inputs.eq(0).css('font-size', '100px');
Should do the trick in this case
see this function .eq() in Jquery-API
When access the Dom-Node-Collection in JQuery via Array-Index, you get the RAW Dom-Elements, if you select the index with the given method above, you'll get feature-enhanced jQuery-Wrapped-Elements.
See docs.
The only way to avoid wrapping each element again($(inputs[0]).css('font-size', '100px'))
would be using pure JavaScript. Example: inputs[0].style.fontSize = "100px";

Get a jQuery element for a DOMElement

I know how to do the opposite. Getting a certain DOMElement for a jQuery element is easy. (Use the get() method)
But how can you get a jQuery element for a specific DOMElement?
Unfortunately this DOMElement does not have any attributes like class or id so constructing a selector is not really an option.
Lets say I have this html:
<div class="edit">Abcd<b><i><u>asdasd</u>adasda</i></b>sdfsdf<br>asd</div>
I am in the u-DomElement. How can I get this as a jQuery element?
Is there a smart way to do this?
EDIT:
I wanted to know if there is a gerneral way to do this. Not specific to the code shown above.
Like:
DomElement.toJQuery()
Is there anything like that? I am aware that this might not be possible.
Getting a jQuery object for a DOM object is as simple as jQuery(dom_node) (or $(dom_node)). See http://api.jquery.com/jQuery/
This is commonly used in event handlers, which are given the DOM node as this, so that you will often see $(this)
If you want to get just the Element use the below code. if you wanted to get the HTML of any element you might want to add the .html() tag to either of the examples
var myVar = $('.edit u');
or
var myVar = $(".edit").find("u");
Are you looking for this?
$(".edit").find("u");
hope this is what you are looking for,
$(DomElement)
you want a only 1 specific dom element i suggest you find a way to add an id to that element.
but to get an u element inside a edit class:
$('.edit u');
$('.edit').find('u');

How to add child tags to a javascript array

I'm trying to fill an array with all direct child elements of a div.
example:
<div>
<span></span>
<a></a>
</div>
should result in an array containing span and a
How Would I achieve this?
I tried var elements = $('.thediv').children(); but that doesn't seem to work.
Also how Would I then use that information for this kind of function?:
$("element1","element2","element3") depending on the result of the array?
Really thank you for your help! I am kind of lost with this thing
Note: I'm using zepto.js which has a similar syntax to jquery but misses a lot of functions so that might be a problem but I am also happy with solutions using jquery syntax because it should work pretty well :) https://github.com/madrobby/zepto
To get the tags into the array, you could easily use, with jQuery (though I'm unfamiliar with zepto):
var elementsArray = [];
$('div').children().each(
function(i){
elementsArray.push(this.tagName.toLowerCase());
});
JS Fiddle demo.
And to use them, you can try:
for(i=0;i<elementsArray.length;i++){
$('div').find(elementsArray[i]).css('color','red');
}
JS Fiddle demo.
Although this simply uses the tagName of each element, so if there is more than one a within the relevant element all elements matching the selector, effectively $('div').find('a') in this case, will be targeted by the selector.
The above caution seems to be discounted through use of a more complicated selector, and behaviour, and allows for each element to be iterated over one at a time, though I can't help but feel it's a little more complex than it needs to be:
var elementsArray = [];
$('div').children().each(
function(i){
elementsArray.push(this.tagName.toLowerCase());
});
for(i=0;i<elementsArray.length;i++){
$('div')
.find(elementsArray[i])
.not('.edited')
.eq(0).css('color','red')
.addClass('edited');
}
JS Fiddle demo.
Sigh, I'm an idiot. The final iteration of this is below, which reduces the complexity somewhat, and allows for proper iteration over each element according to their position in the array:
var elementsArray = [];
$('div').children().each(
function(i){
elementsArray.push(this.tagName.toLowerCase());
});
for(i=0;i<elementsArray.length;i++){
$('div')
.children()
.eq(i)
.css('color','red');
}
JS Fiddle demo.
Having said the above, though, if you want to "target all elements within," why not simply target those elements with:
$('div').children();
Which will select, and target, each direct child of the div element without first holding them in, or having to hold them in, a user-created array variable.
$("div").children().toArray();
http://api.jquery.com/toArray/
$("element1","element2","element3")
Does this mean you want to use the array as a jQuery selector? Or you really want the tag names?
Each DOM node has a childNodes attribute, which is a NodeList containing all the direct descendants of the node in question.

How to retrieve an id of an html element in JavaScript

I want to know is there any way to identify an html element by its "id"?
If so than
how can I call another html element e.g html table by is id all this using java script.
<a id="a" class="menuheader" >New Arrivals</a>
<a id="a1" class="menuheader" >Concepts</a>
I want JavaScript to identify the id of the above two elements and upon identifying the id call another html element i.e a table.
I am not quite sure what you want.
To get an element by its ID, you can use document.getElementById(id).
To get the ID of an element, you need a reference to the element and access the id property: element.id.
To access an object in your DOM by its id you can use document.getElementById("...").
To enumerate the children of a container:
for (var i in containerElement.childNodes)
var elementId = containerElement.childNodes[i].id;
You could always use the jQuery JavaScript framework, which IMO is way better than plain old JavaScript for the most part. In jQuery you would just pass the eleent's ID you want to select (prevexied by the hash symbol to identify the selector is an ID) as a string to the jQuery function. Then , your action would follow a period after the selector
jQuery('#a').actionGoesHere()
But you would more commonly call the jQuery function by it's alias, the dollar sign:
$('#a').actionGoesHere()
Not so sure by what your second part of the question means, so if you clear that up a little, I'd be glad to help.
https://developer.mozilla.org/en/document.getElementById
I think something like this is what you are trying to do if I understand you correctly.
The first one is if you are using named anchors to call your tables
$("a").click(function () {
if ($this.has($("#a"))) { $this.attr("href", "#myfirsttable") }
if ($this.has($("#a1"))) { $this.attr("href", "#mysecondtable") }
});
I haven't had time to try it out yet, and I'm a bit sleepy right now and not at my sharpest, but this is the simplest way I can think of at the moment.

jquery changing innerhtml of a P isn't working

I have what I thought was a simple select with jQuery to change some text on a paragraph. It works perfect the traditional way i.e.
document.getElementById('message_text').innerHTML = "hello";
But with jQuery it doesn't. I have checked the values of $('#message_text') and sure enough I see the items.
$('#message_text').innerHTML = "hello";
Am I doing something wrong?
Anyone have any ideas?
When you do something like $('#message_text') what you have there is not a regular DOM object, but a jQuery wrapped set (even though in this case it'd only be one element.) If you wanted to access a particular DOM property, you could do this:
$('#message_text')[0].innerHTML = 'whatever';
$('#message_text').get(0).innerHTML = 'whatever';
However, this isn't necessary in this case as jQuery has two functions to do what you want:
html():
$('#message_text').html('whatever');
text():
$('#message_text').text('whatever');
The difference between the two is that html() will allow HTML while text() will escape any HTML tags you pass to it. Use the one you need over manually manipulating the HTML with innerHTML.
The jQuery function $() is not returning a HTMLElement object like getElementById() does but a jQuery object. And there you just have the html() method as equivalent to innerHTML. So:
$('#message_text').html('hello');
$('#message_text').html('hello')
jQuery selector returns an array, not a DOM Element node.

Categories

Resources