How to get a DOM Element from a jQuery selector? - javascript

I'm having an impossibly hard time finding out to get the actual DOMElement from a jQuery selector.
Sample Code:
<input type="checkbox" id="bob" />
var checkbox = $("#bob").click(function() { //some code } )
and in another piece of code I'm trying to determine the checked value of the checkbox.
if ( checkbox.eq(0).SomeMethodToGetARealDomElement().checked )
//do something.
And please, I do not want to do:
if ( checkbox.eq(0).is(":checked"))
//do something
That gets me around the checkbox, but other times I've needed the real DOMElement.

You can access the raw DOM element with:
$("table").get(0);
or more simply:
$("table")[0];
There isn't actually a lot you need this for however (in my experience). Take your checkbox example:
$(":checkbox").click(function() {
if ($(this).is(":checked")) {
// do stuff
}
});
is more "jquery'ish" and (imho) more concise. What if you wanted to number them?
$(":checkbox").each(function(i, elem) {
$(elem).data("index", i);
});
$(":checkbox").click(function() {
if ($(this).is(":checked") && $(this).data("index") == 0) {
// do stuff
}
});
Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.

Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:
$('#element').get(0);
I have verified this actually returns the DOM element that was matched.

I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.

If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.
But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.
UPDATE: Based on a comment:
Here is a post with a nice explanation: http://www.mail-archive.com/jquery-en#googlegroups.com/msg04461.html
$(this).attr("checked") ? $(this).val() : 0
This will return the value if it's checked, or 0 if it's not.
$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

Related

How do I make an OnClick function that will change a word when a user clicks it to another word?

Okay so, I want to make an OnClick function in JavaScript that makes it so when a user clicks on it, it will change the word. Is there a replaceword() function or something that which will let me do so? I know this is not real code, but for example:
<p>Quickly <span onclick="replaceword('Surf');">Search</span> The Web!</p>
If there is, then can someone tell me also how to reverse the code maybe? So when they click on it the second time, it will change back to "Search"?
If you want to jump between multiple words, you'll need to store them someplace. You could have two words in the sentence, and toggle the visibility of one or the other (which doesn't scale well), or you could even store them as values on an attribute placed on the element itself.
<p>Hello, <span data-values="World,People,Stack Overflow">World</span>.</p>
I have placed all possible values within the data-values attribute. Each distinct value is separated from the other values by a comma. We'll use this for creating an array of values next:
// Leverage event-delegation via bubbling
document.addEventListener( "click", function toggleWords ( event ) {
// A few variables to help us track important values/references
var target = event.target, values = [], placed;
// If the clicked element has multiple values
if ( target.hasAttribute( "data-values" ) ) {
// Split those values out into an array
values = target.getAttribute( "data-values" ).split( "," );
// Find the location of its current value in the array
// IE9+ (Older versions supported by polyfill: http://goo.gl/uZslmo)
placed = values.indexOf( target.textContent );
// Set its text to be the next value in the array
target.textContent = values[ ++placed % values.length ];
}
});
The results:
The above listens for clicks on the document. There are numerous reasons why this is a good option:
You don't need to wait for the document to finish loading to run this code
This code will work for any elements added asynchronously later in the page life
Rather than setting up one handler for each element, we have one handler for all.
There are some caveats; you may run into a case where the click is prevented from propagating up past a particular parent element. In that case, you would want to add the eventListener closer to your target region, so the likeliness that bubbling will be prevented is less.
There are other benefits to this code as well:
Logic is separated from markup
Scale to any number of values without adjusting your JavaScript
A demo is available for your review online: http://jsfiddle.net/7N5K5/2/
No, there isn't any native function, but you can create on your own.
function replaceword(that, word, oword) {
that.textContent = that.textContent == oword ? word : oword;
}
You can call it like this:
<p>Quickly<span onclick="replaceword(this,'Surf','Search');">Search</span>The Web!</p>
Live Demo: http://jsfiddle.net/t6bvA/6
<p id="abc">Hello</p>
<input type="submit" name="Change" onclick="change()">
function change(){
var ab=document.getElementById('abc').value;
ab.innerHTML="Hi, Bye";
}
I think so this should help you, you should go to site such as w3schools.com, its basic and it will answer your doubt
You can try something like this if you wanna use jQuery
http://jsfiddle.net/R3Ume/2/
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<body>
<p>Hello <a id='name'>John<a></p>
<input id="clickMe" type="button" value="replace" onclick="onClick();" />
<script>
function onClick() {
$('#name').text('world');
}
</script>

jQuery .html() | Will it include inline style?

Say I have something like this setup.
<div id="error">
<p style="color:green">Success.</p>
<p style="color:red">Failure.</p>
<p style="color:green">Success.</p>
</div>
and in my javascript I run something like this.
var response = $('#error').html();
if (response.indexOf('red') === -1) {
/*do stuff if #error has no style tags that have the color:red*/
}
Will that work or do I need to go about doing this a different way? I'd like some insight, thanks.
So how should I go about this if thats not the best way?
The best way (or a better way) would be to give a failure class to p elements rather than trying to check against styles. But if you have no choice...
DEMO
There are various ways, the first one is closer to your initial line of thoughts:
if ($('#error > p[style*="color:red"]').length) {
console.log('red');
}
A different approach which is slightly better in my opinion:
var redPs = $('#error > p').filter(function () {
return this.style.color === 'red';
});
if (redPs.length) console.log('red again');
Yes it will take inline CSS. If you have tried opening up a console, you have known that.
However seeing your need. I recommend using Jquery data attribute. Passing jQuery data attribute you can find whether the message is an error or success.

Jquery multiple selector

I am trying to select one input box, But because i may have more than one inputs, i am trying to limit the one i am selecting. Here is my jquery code that select the the input but for some reason it doesn't work. Is theresomething i am doing wrong? This is be executed once the document is ready.
if ( $("input[name='RETURN.URL'][value='http://link.com?TYPE=P&PID=ST-L09F166&CONSTITUENCY=WBST']").length > 0 )
{
alert("Transcript report");
}
else
{
alert("Not Transcript Report");
}
Here the html
<input type="hidden" name="RETURN.URL" value="http://link.com?TYPE=P&PID=ST-L09F166&CONSTITUENCY=WBST">
<input type="hidden" name="SUBMIT_OPTIONS" value="">
Your selector is using the HTML escaped attribute value:
[value='http://link.com?TYPE=P&PID=ST-L09F166&CONSTITUENCY=WBST']
The actual value of the selector should use & and not &:
[value='http://link.com?TYPE=P&PID=ST-L09F166&CONSTITUENCY=WBST']
The value was HTML escaped so that the value would be correctly represented within the attribute, but the query selector needs to match by the actual value.
You'd probably be better off using a simple selector such as a class. This is particularly important, as the URL represented in the [value] attribute could have its query string parameters in any order and represent the same resource.
HTML entities are translated before they're shown in the browser, therefor & becomes & and so forth. So when you're filtering the selector you're looking for something that's been translated into something else.
Here's the JSFiddle.
Without getting into details of why you're selecting input elements this way, you just need to understand what I said and change the selector to:
$("input[name='RETURN.URL'][value='http://link.com?TYPE=P&PID=ST-L09F166&CONSTITUENCY=WBST']")
use jQuery attr() method
if($("input[value='http://link.com?TYPE=P&PID=ST-L09F166&CONSTITUENCY=WBST']").attr('name') == 'RETURN.URL'){
alert("Transcript report");
}
else
{
alert("Not Transcript Report");
}
Unless otherwise, these contents are dynamically added, it is better to give this input an id, and access via it.
lose the dot in RETURN.URL (its not a preferred way of adding names with dots to input elements)
& use $('input[name=RETURNURL]').val().length
Check the value instead of using it as a selector.
JSFiddle
if ( $("input[name='RETURN.URL']").val().length > 0 )
{
alert("Transcript report");
}
else
{
alert("Not Transcript Report");
}

How to select children and self with jQuery?

I'm wondering what the best way is to find children of an element in jQuery, but also include the parent in the 'find'.
Here's my simplified basic HTML setup:
<div id="container">
<form id="form1"> <!-- form 1 content --> </form>
<form id="form2"> <!-- form 2 content --> </form>
</div>
And I want a function like this...
function getForms ($container)
{
// Option 1
var $allForms = $container.find('form').andSelf().filter('form');
// Option 2
var $allForms = $container.find('form');
if ($container.is('form')) $allForms.add($container);
// Should return all the forms in the container if passed $('#container')
// Or return just one form if passed $('#form1')
return $allForms;
}
I'm fairly certain that both option 1 or 2 will work. Does anyone know which option above is more efficient? Are there other options which are more elegant or more efficient?
EDIT:
I wasn't happy with the .is() in option 2 because it didn't work when the container had multiple jQuery objects in it. So I came up with something like this:
// Option 3
function getContainerElements ($container, selector) {
return $container.find(selector).add($container.filter(selector));
}
I haven't tested it too much, but I think it'll work for all general cases.
Option 2 is better according to JSPerf tests (Tested in Chrome on linux)
You can see the results here and the tests if you want to try it in different browsers:
http://jsperf.com/children-and-self
Note: I've updated this test to use divs instead of forms (because forms inside other forms don't work: Form inside a form, is that alright?) and we want to test the case where the parent should be added to get the real performance impact as per comment below
EDIT
Added third option performance as requested in comment
If you are really only looking for a single element rather than a set of elements, then the following should work at least as well as your option 3 and be faster:
function getContainerElements ($container, selector) {
var filtered = $container.filter(selector);
return filtered.length ? filtered : $container.find(selector);
}
In case there are both descendant and root elements matching selector, this will return only the matching root elements, unlike your option 3, which will put everything together. If you do want that, then modern jQuery allows a simpler solution:
function getContainerElements ($container, selector) {
return $container.find(selector).addBack(selector);
}

Change input value based on another input's value

hope that title makes sense. I'm a noob at javascript. What I want to do is have a form which will have a couple of inputs like, name and url for example.
When the user enters their name, I'd like the url input to automatically have as a default their name with an underscore between words. So if they type in as their name pedro kinkybottom then automatically set as the default in the url input would be pedro_kinkybottom.
I'm using cakephp if anyone happens to know a particularly cakey way to do this that'd be cool but otherwise any help at all would be most welcome.
Thanks,
Pedro
You'd probably want to do this in JavaScript and not in PHP. Even though you may be more familiar with the latter, the user experience would be better with the former and the overall design simpler (since the page wouldn't need to refresh).
You essentially need to do two things:
Set the value of an input in response to an event on another input.
Replace space characters with underscore characters.
For the second part, take a look at JavaScript's replace function. It's pretty robust and lets you do a lot of string manipulation. Definitely worth trying it out yourself.
For the first part, here's an example with jQuery:
$('#inputName').change(function() {
$('#inputURL').val($('#inputName').val());
});
This would set the value of inputURL to the value of inputName any time the value of inputName changes. For the string replacement, you'd modify it similar to this:
$('#inputName').change(function() {
$('#inputURL').val($('#inputName').val().replace(' ', '_'));
});
Note that the change event will be fired when the control loses focus. If you want to to happen as-you-type then try the keyup event. There are other events as well.
Add a keyup event to the name field that will update the url field:
<form>
<input type="text" id="name" />
<input type="text" id="url" />
</form>
...and the js:
addEvent(document.getElementById('name'), 'keyup', function () {
document.getElementById('url').value = this.value.replace(' ', '_');
});
function addEvent(ele, evnt, funct) {
if (ele.addEventListener) // W3C
return ele.addEventListener(evnt,funct,false);
else if (ele.attachEvent) // IE
return ele.attachEvent("on"+evnt,funct);
}
http://jsfiddle.net/XKEh5/
If you're only going to do some trivial stuff like this, then you'll be fine with plain old javascript. If you're going to be doing a lot of this sort of thing, plus any effects like fading out elements or whatnot, I suggest you look in to mootools or jQuery.
Here is an edited version of the above answer. There was an issue with the "value.replace(' ', '_');" where it would only take the space out between the first two words typed in. This code snippet below does it for all.
<script language="javascript" type="text/javascript">
addEvent(document.getElementById('name'), 'keyup', function () {
document.getElementById('url').value = this.value.split(' ').join('');
});
function addEvent(ele, evnt, funct) {
if (ele.addEventListener) // W3C
return ele.addEventListener(evnt,funct,false);
else if (ele.attachEvent) // IE
return ele.attachEvent("on"+evnt,funct);
}
</script>

Categories