jQuery Selector equivalent of javascript - javascript

I am trying to get the jquery equvaliant of this javascript
var id = $(this).parent().parent().parent().attr("id");
document.getElementById(id).getElementsByClassName("addcomment")[0].style.display = 'block';
but its not working
$('#+id+' '.addcomment').css('display','block');
Any suggestions ?

$('#' + id + '.addcomment').css('display','block');
as a sidenote in the page you should have only one element with that id, so
$('#' + id ).css('display','block');
should works too (of course only if classname it's not necessary to target it, since this is a different selector)

$('.addcomment', '#' + id).css('display','block');
or just simple
$('#' + id).css('display','block');

I think you need to get the child elements based on their class. So try this.
$('#' + id ).find('.addcomment').show();

Related

How to change Jquery selector based on an param passed through a function

I have a function:
function factCheck(index) {
if (arrayOfSites[index].indexOf("pdf") > -1) {
$('#20').attr('style', 'color: red');
$('#' + index).attr('style', 'color: red');
console.log('index: ' + index);
console.log($("#" + index).text());
}
}
So my question is. The text color of the element changes color when I use $('#20') but when I use, $('#' + index) it doesn't work.
Funny thing is, I with console.log.. it logs the text of the element but I can't effect the css of it.
Why is this happening?
// after a three hour meeting.. I came back with some really great answers!! Thank you!!
edit:
the code below shows how I'm snagging all the links on the page and add the id equal to the index of that item. So that's why I'm trying to grab that link, and effect it in some way. I appreciate all you guys.. I think I'm going to take the string and add a letter to it as they come in through the function and then manipulate the anchor from that point. I just wonder if there's a more efficient way of doing this.
$(".lpage a").each(function (index) {
// console.log(index + ": " + $(this).text());
str = $(this).attr('href');
arrayOfSites.push(str);
str = arrayOfSites[index];
title = $(this).attr('title');
parseURL(str);
$('.colContent2').append(cellOpen + '<a onclick="whichFunction(' + index + ');" id= "' + index + '"style="cursor:pointer;" class="injectedLinkCol2" >' + str + '</a>' + cellClose).prop("id", index);
});
Maybe it has something to do with the name of your id attribute. Take a look at this answer.
Try to use the toString() function:
function factCheck(index) {
if (arrayOfSites[index].indexOf("pdf") > -1) {
$('#20').attr('style', 'color: red');
$('#' + index.toString()).attr('style', 'color: red');
console.log('index: ' + index);
console.log($( "#" + index.toString() ).text());
}
}
An id name or class name must begin with a name must begin with an underscore (_), a hyphen (-), or a letter(a–z).
So something like
'#d20'
would work.
See this: Valid CSS Selectors.
I couldn't reproduce the exact problem. I made a pen (link) and tried what you asked but it works well. So it must be some error in the remaining code.
on a related note
In CSS id's are not allowed to start with a number(classes are allowed). So writing something like
#20{
color: red;
}
won't work, but the rule only applies to css. JQuery will still work, which means your only option's are to write inline styles or use JQuery's .attr or .css, but jQuery.attr() will reset all your inline styles. you are left with using .css(). So, it's better to not start your id's with numbers.
try using .css instead of .attr and see if it works.
$('.exampleClass:eq(' + index + ')').css("color", "yellow");
for some reason works
$('.exampleClas').eq(index).css("color", "yellow");
does not work.

jquery - using the .change even on a select drop down list to filter results

my code is:
$('select').change(function(){
$('.sep14, .oct14').hide();
var userChoice = "'." + $('select').val() + "'";
$(userChoice).show();
});
So, when the user changes the dropdown list the two divs with those classes hide and then the variable stores the userChoice as something jquery can recognise which is then shown again, using .show().
For some reason though, this doesn't seem to work, anyone know why?
Thanks
You don't have to use ' on var userChoice = "'." + $('select').val() + "'";
Code :
$('select').change(function() {
$('.sep14, .oct14').hide();
var userChoice = "." + $('select').val();
$(userChoice).show();
});
Demo
Also, this is somewhat weird way to achieve what you are doing, consider using data- attributes instead where you can create custom attributes with values, which are completely valid as of HTML5 like :-
$('select').change(function(){
$('[data-toggler]').hide();
$('[data-toggler=' + $(this).val() + ']').show();
});
Demo 2

How to provide elements/tags dynamically inside the find() in jquery

I have created several div with id's such as window1, window2 and so on. Now all I want to is find the tag from these above created divs. I am doing this inside the for loop but it is not working for me. Here is what I am doing
for(connectWindow=1;connectWindow<=xmlLength;connectWindow++)
{
//look for the to tag inside the html
var windo = "window"+connectWindow;
var to = "to"+connectWindow;
alert("Making connections" + windo +to)
//$("div#windo").find('strong#to')(function())
$("div#windo").find('p#to').each(function(){
alert("####################");
var name = $(this).text();
//display_function(name,country);
alert("Name is :::"+name);
});
}
Please let me know where I am going wrong. Also please let me know if there is any solution in JavaScript either.
Thanks !
You need to do it like this
$("div#" + windo).find('p#' + to).each(function(){ // <-- this uses your variable
alert("####################");
var name = $(this).text();
//display_function(name,country);
alert("Name is :::"+name);
});
Your code looks for an id="window" and id="to" instead of your variable
$("div#windo").find('p#to')
You really can just do it by ID since you are using the #(id selector)
$("#" + windo).find('#' + to)
Well, you need to actually use the variables:
$("div#" + windo).find('p#' + to).each(function(){
By the way - jQuery is written in JavaScript. If you're using jQuery, you're using JavaScript.

Change the type of element using jQuery

If I know the ID of an element, is it possible to change the type of HTML tag that it has?
For example if you have <p id="p">Lots and lots of text here.</p>, is it possible to change it to <span id="p">....?
Thanks.
You can use the replaceWith method to do this. You'll need to rebuild the attributes for the replacement though.
$('#p').replaceWith(function(){
return '<span>' + $(this).contents().text() + '</span>';
});
Working example
You can do this:
var a = $('#p').text();
$('#p').replaceWith('<span id="#p">' + a + '</span>');
http://jsfiddle.net/teBuN/
var el = document.getElementById(id);
var new = document.createElement("span");
new.id = el.id;
[].forEach.call(el.childNodes, function (node) {
new.appendChild(node);
});
el.parentNode.replaceChild(new, el);
Now, a good question, is why. Why would you want to change the html element?
Surely you choose the most semantic element for this piece of data, why would another element be a better choice?
$("p").replaceWith(....) .............

Best way to GET the xpath and css selector of a specific element

Looking for the best way to GET the xpath and css selector of a specific element using jQuery or Extjs. To basically select a random element and traverse up the dom and retreive it's unique css selector or xpath. Is there a function that can do this already or does anyone have a custom function that can do this?
Why not just check for an "id" value, and if there is one there just use it. If there isn't one, generate a unique random "id" value, give it to the element, and then use that.
edit: here's a proof-of-concept jQuery hack to build up a selector for any element you click on.
$('*').unbind('click.m5').bind('click.m5', function(ev) {
if (this != ev.target) return;
var cn = function(elem) {
var n = $(elem).parent().children().index(elem);
return elem.tagName + ':nth-child(' + n + ')';
};
var selector = cn(this);
$(this).parents().each(function() {
if (/BODY|HTML/.test(this.tagName))
selector = this.tagName + '>' + selector;
else
selector = cn(this) + '>' + selector;
});
console.log("Selector: " + selector);
$(selector).css('background-color', 'red');
});
There are an infinite number of selectors for any given element. What do you need it for? You might be able to use Firefox plugin like XPather?

Categories

Resources