jQuery '#' + data("target") pattern - javascript

I've seen this a bunch:
Click me
<div id="content">And something will happen here</div>
With JS like this:
$("#trigger").click(function(){
$("#" + $(this).data("target")).hide();
})
It looks a little weird to me to be doing this string concatenation to create selectors which are then used to get the target element. Is there a better pattern in Javascript (with jQuery available) for setting up handlers on one element which need to know about another target element?

Why you do string concatenation just store the id with #
Click me
$("#trigger").click(function(){
$($(this).data("target")).hide();
})
Similarly you can store any selectors as is in data-target say for ex:- .tab1 etc so that you do not have to perform string concatenation again inside the click or any event.

You can simply use
$('#content').modal('toggle');
Any where in you're code to initiate the modal show and hide,
You can use even "show"/"hide" functionality directly.
I assume you're using Bootstrap and one of the latest versions of jQuery.
Enjoy !

Why not do something like this, a much better approach in my opinion:
// Set the target
$("#trigger").data('target', $('#content'));
// Get the target
$("#trigger").click(function(){
$(this).data("target").hide();
})
If you're setting it from the backend, I would include the hash with the attribute value as others have suggested.
Click me
$("#trigger").click(function(){
var target = $(this).data("target");
$(target).hide();
})

You always have the option to build the selector, looks a bit nicer than concatenating the string inside the selector.
$("#trigger").click(function(){
var selector = "#" + $(this).data("target");
$(selector).hide();
});
A little nicer, not sure if it's what you're looking for.

I would skip the data- completely, thus allowing graceful degradation.
Click me
<div id="content">And something will happen here</div>
with
$("#trigger").click(function(e){
e.preventDefault();
$( $(this).attr("href") ).show();
// note, i'm purposly not using this.href due to a bug in IE that would return the entire href rather than just the hash
})

$(this).attr('data-target', '#myTarget');
this worked for me

Related

This jQuery toggleClass behaviour seems strange, am I doing this correctly?

I have a CSS rule for hiding elements with a class="hidden" and I'm using jQuery to toggle this class on and off on whatever ID i click on so I can make elements disappear.
Why does this not work?
$(this).attr('id').toggleClass("hidden");
but this does?
var x = "#" + $(this).attr('id');
$(x).toggleClass("hidden");
I know that the id is being taken correctly on the first example, but it seems that to toggle the class I have to add a "#". I haven't seen any examples of others having to resort to this so I'm wondering what madness I have here.
Many thanks
$(this).attr('id').toggleClass("hidden");
You are chaining events here. $(this).attr('id') already returns you a string. So you are technically doing "someid".toggleClass("hidden") which doesn't makes sense.
In your second example, you are actually selecting the same element again via id and firing your method, which is right
.attr('id') returns a string, not an element.
Let's pretend your element has an ID of myThing. Here's what your code translates to:
// 1
"myThing".toggleClass("hidden");
// 2
var x = "#myThing";
$("#myThing").toggleClass('hidden');
But really, if you're getting the ID from this, there's no reason to extract the ID in the first place. Just use this directly.
$(this).toggleClass('hidden');
You can simply use:
$(this).toggleClass("hidden");
$(this) is the actual element you're working with, so you can use this to directly toggle classes with.
In your examples, $(this).attr('id') is a string, and not an element.
This code works, because you're taking the ID (As a string), and selecting the ID on the webpage.:
//Store the id into a string
var x = "#" + $(this).attr('id');
//Pass the ID back into jQuery, and find the element
$(x).toggleClass("hidden");

Why I can not change the href value by jQuery?

Below is my code..
var content = $("XXXX");
content.find("a").each(function() {
var value = $(this).attr('href');
$(this).attr('href', encodeURI(value));
alert(value);
});​
However, it keep showing error.
How can I make this code work which I want to encode the url.
Instead of content.find('a') use content.filter('a'). Because right now you're content is an array of only one element (ie. <a>), so there is no more <a> within that <a> and .find('a') fails here.
So .filter() is safe to use.
Demo
No need to use JQuery.find here as content variable has only anchor tag and you want to apply encodeURI for your URL.
For that requirement below code is well enough.
$(content).each(function(){
var value = $(this).attr('href');
$(this).attr('href', encodeURI(value));
alert($(this).attr('href'));
}
);
Hope it helps you.
maybe you should add an ID (if you want to use this for more than one element then create a specific class for the elements and link via $(".classname")) to your link and then use a normal query like this
var yourLink = $("#yourID");
yourLink.attr('href', encodeURI(value));​
and make sure that your value has something in it. Also if .attr(...) has still no effect please try .prop("href", encodeURI(value))

Is it possible to grab a link by its href if it doesn't have a class or ID?

I'm using someone else's app and want to change the innerHTML in between any < a>< /a> tag that has a certain href. But these links don't have a class or ID associated with them and I can't edit the code to give them classes or ID's. Is there a way to grab a tag by its href in JavaScript? I wanted to do something similar to this:
var theLink = document.getElementByHref("example.com");
Otherwise, if that is not possible, can I loop through all the links in the page and choose the ones that have the certain href and innerHTML I'm looking for?
You can use a DOM3-attribute-selector (jQuery doc) to get all elements that contain a certain text in their href attribute. It would look like
$('a[href*="example.com"]')
However, that might not be what you actually want - not only urls to that domain might contain this string. You might do something like begins-with:
$('a[href^="http://example.com"]')
but to get an exact and possibly more complex match, you don't get around a custom filter:
$('a[href]').filter( function() {
return this.hostname == "example.com";
// or check other properties of the anchor element
})
Select all elements that have the example.com value in href attribute:
Live Demo: http://jsfiddle.net/NTGQz/
$('a[href*="example.com"]');
You can also try this, just to be more specific and following the OP "ideal" answer:
Live Demo: http://jsfiddle.net/ksZhZ/
jQuery.fn.getElementsByHref = function(str){ return $('a[href*="' + str + '"]'); };
$(document).ready(function(){
elems = $(this).getElementsByHref('example.com');
});
jQuery has a lot of selectors. The one you want here is the attribute selector.
$('a[href="example.com"')
You can use an attribute selector:
$('a[href="http://example.com"]')
With JQuery attribute selector, you can do this :
$('a[href="example.com"]')
Try this
$('a[href*="example.com"]');
This will select the link that has example.com in the href attribute..
$('a[href="http:google.com"]')
you can do it with jquery: http://api.jquery.com/attribute-equals-selector/
ex: linksToGoogle = $('a[href="http://google.com"]');
You can do this without jQuery.
var links = document.querySelectorAll('a[href*="example.com"]');
You can do this natively with querySelectorAll if your users are on IE8+ or any other browser. This method returns an NodeList of matching elements.
document.querySelectorAll('a[href="exact/value.html"]'); // exact match
document.querySelectorAll('a[href*="partial/value.html"]'); // partial match
document.querySelectorAll('a[href^="starts/with"]'); // href starts with
document.querySelectorAll('a[href$=".html"]'); // href ends with

Adding a jQuery Click handler

I have following div in a page (I can not modify).
<div id=":0.control">Click me</div>
Now I want to add a jQuery Click handler
$("#:0.control").click(function () {
alert('Clicked');
}
);
Above gives error. Any solution??
Instead of
$("#:0.control")
try
$('div[id="\\:0\\.control"]')
DEMO
or
$("#\\:0\\.control") // better that previous one
DEMO
You can escape special characters in selectors:
$("#\\:0\\.control").click(function () {
alert('Clicked');
});​
Here's a working example.
Note that unless you are using the HTML5 doctype, your ID is invalid. Also note that escaping the special characters is significantly faster than using an attribute selector as in another answer:
The reason for this is that the browser can take advantage of the speed of getElementById, rather than having to rely on querySelector or Sizzle.
This is ugly,but it works:
$(document.getElementById(":0.control"))
In cases, when id is stored in variable, you have to use:
var id = ":0.control";
$(document.getElementById(id))
Otherwise, when you want to use pure jQuery, you need to add additional slashes.
More complex example:
var idArray = [":bla-bla","bla[]","commonId"];
$.each( idArray, function(i,id){
$(document.getElementById(id)) //do some stuff
//Otherwise, when using pure jQuery, we need to add slashes before ':','[',']' characters
});

jquery- store id of clicked link in variable

This should be basic, but for some reason its not working for me. I just want to store the id when a link that has a certain class is clicked in a variable so as an example:
Some link
I would want jquery to get the id of the link above and store it in a variable. I have tried $this.attr("id") and $this.id, but non of this worked.
This is what I have for the jquery:
$(".only_this_class").click(function() {
var clickedId= $(this).attr("id");
alert(clickedId);
});
I just get "undefined" every time.
I removed the space between this and _class in class="only_this _class" and it is working for me.
Try this here
Please have a look at jQuery Selectors
If you have two classes in your HTML then the syntax is different:
$('.classA.classB')
Have a look at How can I select an element with multiple classes?
NAVEED is right, if you remove the space it works, because if there is a space HTML will put two classes on the element: only_this and _class.
If you are in fact looking for two different classes, you should replace the space with a dot to make it work properly, as in $(".only_this._class")
$(".only_this _class") this selector will look for _class tag in .only_this element. May you are looking for $(".only_this") which will select element which has this class. Try this.
$(".only_this").click(function() {
var clickedId= $(this).attr("id");
alert(clickedId);
});

Categories

Resources