JQuery: find element whose class contains value of variable [duplicate] - javascript

This question already has answers here:
How to use JavaScript variables in jQuery selectors?
(6 answers)
Closed 7 years ago.
I searched high and low now but I can't figure out how to get this to work:
I need to get the element whose class name contains a number that I pass with a variable.
For better understanding: This is inside a "click" event on a gallery. Whenever an img is clicked I search for the src, see which number the string contains and then want to find the matching p whose class contains the same number. So I can manipulate the matching text to the picture that is currently displayed (Since the plugin I use strips away any id or class I can only identifiy a picture by its source name).
So far it does work if I directly put the number in as a String. Like this:
var team_t = $(this).find("img").attr("src");
for(n = 1; n <=6; n++ ){
if(team_t.indexOf(n) != -1)
{
$('#text_content').find("p[class*='3']").css("background-color", "red");
}
}
But instead of "3" I want it to get the number that the variable n holds. I tried this but it did not work:
$('#text_content').find("p[class*=' + n + ']").css("background-color", "red");
Actually it didn't work with any kind of variable I tried to pass. I also saw and tried examples that use contains( ) or hasClass( ) and others.. but nothing worked for me. I'm not extremly familiar with the syntax though.
How do I have to write this so it takes the variabel as a string?
If I do alert( n ) it shows the correct number, so that's not the problem.

You were on the right track with string concatenation, you just didn't get all the way outside the string:
$('#text_content').find("p[class*='" + n + "']").css("background-color", "red");
// Change is here -----------------^- and -^
In your attempt, the + n + was still in the outer quotes, and so was used literally in the selector (making it fail).
That said, if you have any control over the DOM structure (but it sounds like you may not), there's probably a better way. For instance, you could put a data-* attribute on the element that gives an appropriate selector for the p element (possibly even by id, but that's just one option).
You might also want to end the loop once you've found the index, by putting break; on the line after the line setting the red color.
Finally: You might want to use a class to add the red color rather than mixing your presentation into your JavaScript code.

Related

Make 1 javascript/function affect several classes at once - how?

I am using the following code on my webpage, in order to format certain numbers (with the ".pricetag" class), as i need to show them as currencies (comma separated at thousands) on my front end:
jQuery(document).ready(function($) {
$.fn.digits = function(text){
$(this).text(text.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + '€' );
};
var tempText = $.trim($(".pricetag").text());
tempText = tempText.substr(0, parseInt(tempText.length) );
$(".pricetag").digits(tempText);
});
So far so good - code works fine, and does what i need it to.
My problem is that i have more classes than just the ".pricetag" class, for which i want to use the function. So right now i have copy pasted the code, and just changed the target class (".pricetag_2" etc.).
How do i tell one version of the javascript/code, to affect several classes (both ".pricetag" and ".pricetag_2") in stead of having to copy paste the same piece of code, let's say 10 times, to target 10 different classes.
It's a bit overkill to have so much code, as the function is exactly the same every time. In CSS it's pretty easy, as you can affect several classes at once, by comma seperating them within a piece of code, but how do i do it in javascript?
Thanks!
If all your classes begin with .pricetag you might try the attribute-starts-with selector.
$("[class^='pricetag']").digits(tempText);

Select class name (number) using RegEx & Jquery

I have a element like this
<div class="th-class2 th-hhjjsd th-context-78474378437834873"></div>
(Note: I know class names should not be pure numbers)
I want to get the numerical number from this div.
id = 78474378437834873
Is there a way I can use regular expressions to do it. I am nearly there but it only returns the first 4 numbers.
I use a clickevent to target the div and try and get the class like this
var classString = $(this).prop("class").match(/([0-9]+)/)[1];;
console.log(classString)
result is 7847
I am just not understanding how to get the rest of the number.
Thanks
You shouldn't use integers for class names because using a class typically means you are going to use the element more the once and adding a dynamic number defeats the purpose of classes, also working with someone else code and they use integers it's very hard to understand their code. As far as your questions goes, you shouldn't really use regular expressions to get a value of a class you should either store the value as an id so your element would look like this,
HTML
<div id="78474378437834873" class="th-class2 th-hhjjsd"></div>
or you could use a data object which is how I would do it like so,
HTML
<div class="th-class2 th-hhjjsd" data-object='{"value":78474378437834873}'></div>
and then when you select your element with your click event to get the value of the element you clicked console log the elements data object like so
jQuery
$('.th-class2').click(function() {
console.log($(this).data('object').value);
});
You should not use number only class names, they must start with an Alpha character [a-Z]
You can find what are the allowed characters in this discussion: Which characters are valid in CSS class names/selectors?
(Please make sure to read also the comments).
As per a solution for you,
The easy solution would be to use data attributes as so:
<div data-id="1000"></div>
and then you could get your id as simple as:
$(this).on('click', function() { console.log($(this).data('id')); } );
Happy Coding.

Replace multiple string instances in javascript [duplicate]

This question already has answers here:
How do I replace all occurrences of "/" in a string with "_" in JavaScript?
(4 answers)
Closed 8 years ago.
String contents :
background:url(abcd.gif); background:url(images/header2.gif) no-repeat;
background:url(images/bullet1.gif) no-repeat 11px 13px;
Javascript Code :
var testRE = originalcode.match("url\(\(.*)\)");
testRE = testRE[2].replace('(','');
testRE = testRE.split(')')[0];
var img_path = "http://xyz.com/800002418/"+testRE;
originalcode = originalcode.replace(testRE,img_path);
In the above code it's only replacing first instance of match. I am trying to replace multiple instances for url in string like above are 3 instances in string for url. But it's only replacing 1st instance and that is "abcd.gif" to "http://xyz.com/800002418/abcd.gif". And rest is as it is.
I suspect what you're actually trying to do here is as follows:
originalcode = originalcode.replace(/url\(([^\)]*)\)/g, "url(http://xyz.com/800002418/$1)");
See #Phylogenesis's answer for how to do what you seem to think you want to do, but is that what you really want to do? After you've modified the string, what are you going to do with it? I suppose perhaps you're going to set it as the string CSS value on some element, as in elt.cssText=. But why do you think three background properties in a row are going to do anything useful? Each one will just override the previous one.
Taking a step back, instead of trying to manipulate CSS declarations as strings using regexp's, I suggest manipulating individual property values. So, something like
foo.style.backgroundImage=foo.style.backgroundImage
.replace(/\(.*)\)/,"http://..."+$1);
But I'm still confused as to why you would want to do this. I guess it's because the remote URL is only known at run-time? The most flexible solution is to place a CSS file on the host in question and load it. If the images are there, you ought to be able to arrange to put a CSS file there along with them. The URL references in the background property values will then automatically be interpreted in terms of the URL of the CSS file, without having to rewrite in this ugly fashion.

jQuery, how to test of a variable is a text node, containing no markup?

http://jsfiddle.net/DerNalia/zrppg/8/
I have two lines of code that pretty much do the same thing
var doesntbreak = $j("hello");
var breaks = $j(" ");
​The first one doesn't error, but the second one throws this
Syntax error, unrecognized expression:
should'nt they both behave the same?
any insight as to how to solve this?
in the actual method I'm using, ele is from the Dom, so it could eb a text node, or any other kind of node.
UPDATE:
the input to the function that I'm using that I noticed this takes selection from the dom.
updated example: http://jsfiddle.net/DerNalia/zrppg/11/ <- includes html markup.
So, I guess, my question is, how do I test if something is JUST a text node? and doesn't contain any markup?
In general, you cannot create standalone text nodes with the jQuery function. If a string isn't obviously HTML, it gets treated as a selector, and is not recognized by jQuery as a valid selector.
Assuming you want to parse arbitrary strings (which may have HTML tags or not), I suggest something like var result = $('<div></div>').html(' ').contents();. Place your your HTML or text string in a div to parse it and then immediately extract the parsed result as a jQuery object with the list of elements. You can append the resultant list of elements with $(parentElem).append(result);
try this:
function isTextNode(node){
div=document.createElement('div');
div.innerHTML=node;
return $(div).text()==$(div).html();
}
And " " is'nt a valid selector if you want to find a elements containing some text you must use the :contains selector http://api.jquery.com/contains-selector/
Internet Explorer (older versions at least) don't have built in "querySelector" functions, so the Sizzle engine has to do the work directly. Thus, the slightly different tolerances for bogus input can cause differences in error reporting.
Your selector expression " " is equally invalid in all browsers, however. The library is not obliged to quietly accept anything you pass it, so perhaps you should reconsider your application design.
If you want to check for entities, you could use a regular expression if you're confident that it's just a text node. Or you could get the contents with .text() instead of .html().
So, I have to thank Apsillers and Rolando for pointing me in the right direction. Their answers were very close, but gave me the information I needed.
This is what I ended up using:
TEXT_NODE = 3;
objectify = function(n) {
return $j("<div></div>").html(n).contents();
}
function textOnly(n) {
var o = objectify(n);
for (var i = 0; i < o.length; i++) {
if (objectify(o[i])[0].nodeType != TEXT_NODE) {
return false
}
}
return true;
}
And here is a jsFiddle with some test cases, that neither of the original code submissions passed.
to pass, it needed to handle this kind of input
"hello" // true
"hello<b>there</b>" // false
"<b>there</b>" // false
" " // false
Not actual answer, but may help someone with similar issue as mine and loosely related to this question. :)
I was getting same issue today, so fixed by removing
Changed:
var breaks = $j(" ");
to:
var breaks = $j(" ".replace(/&.*;/g, ""));
Here I am removing , < etc...
Note: value at is dynamic for me, so it can be anything.

Using a variable when traversing elements in JQuery

Very quick and hopefully simple question.
I am trying to select a hidden input by value with some predefined variable.
var id = $("#puid").val();
$('input[value=id]').closest('tr').css({'background-color':'red'});
I thought the above code would have worked, however its not processing id as a variable. What is the right notation to do this? (I have tested the code by replacing id with the actual number and the rest of the code works fine).
remove it from the quotes, so the variable is concatenated into the string. They way you have it, it's looking for the literal value "id", and has no way of knowing that you're talking about a variable.
$('input[value='+id+']')
edit: more info - you could put double quotes around the id part, inside the strings, as in Nick's answer, which would make it safe to use with non-numeric ids. I omitted them since your example doesn't need them, as you said your ids are numeric.
Concatenate the string selector with the variable, like this:
var id = $("#puid").val();
$('input[value="' + id + '"]').closest('tr').css({'background-color':'red'});
Currently, it's looking exactly for this: value="id", but you want your variable there.

Categories

Resources