How to get element by both id and class - javascript

Is there any alternative solution (in JavaScript) for document.getElementById(); to select a specific element, specifying both the class and id ?
for example I have such a content:
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="2"></div>
And I want to select the corresponding div under the "Question X" link in the function
function showQuestion(id)
{
var thediv = GetByClassAndId("q_content",id); // how to implement this function ?
WriteQuestionIn(thediv); //Ajax
}
Thanks in advance.

you can try document.querySelector()
like document.querySelector(".q_content#2") use the para like css selector..

Since ID is always unique (unless u make a mistake) u have no need to use both class and id to select the element.
Such an approach is not correct, and should be avoided at all cost.
What I suspect is your problem, is that the ID is only a number. Try adding a prefix which is a letter. Do view source to this page to see examples.
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="q1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="q2"></div>
function showQuestion(id)
{
var thediv = document.getElementById("q"+id);
WriteQuestionIn(thediv); //Ajax
}

Actually there is a function $ in jQuery for doing this operation. If you are using any framework, then you should remember there is always a jQuery library available. Else if you are using custom PHP, then add one of them like jQuery or other because they provide lots of types of selectors.
Now here is the code after adding jQuery:
$("#yourid") //basic selector
$("#yourid.yourclass").show()
Use .show() to show the selected element
Use .hide() To hide element

Related

Using jQuery, how to specify with the `.attr` method, the second of two html classes?

When using jQuery and are using the .attr method as follows:
$(document).ready(function(){
$('.class1').click(function(){
id = $(this).attr('.class2');
});
});
Say I have the following HTML for the above function:
<div class="class1 $class2"></div>
The second class is attributed at runtime, so I have 10 divs, each with class1, but several with class2. Then I wish to use the jQuery function at the top, so that whenever I click on any of the divs, it applies the specific class2 of that div, to the variable ID.
I hope this makes more sense.
Since your class2 comes from your PHP code, you seem to hit the usecase of data-attributes.
With data-attributes you can easily have some extra data (often used for javascript purposes) on your HTML elements without having to use special classes or ids for that.
It works like that:
<span data-hero="batman">I'm a Bat!</span>
Where in your Javascript (using jQuery) you get the value of it by simply doing:
$('span').data('hero');
Refer to the MDN and the jQuery documentation for further information.
Is this what you're trying to do?
$(document).ready(function(){
$('.class1').click(function(){
var id = $(this).attr('class').replace('class1','').trim();
});
});
If you have a multi class tag this mean the HTML code would be like this:
<sometag class="class1 class2">...</sometag>
I think the simplest approach is to do some string operations on the class attribute of the tag:
var class2 = $(selector).attr("class").split(" ")[1];
OR you can write a simple jQuery plugin to do the work for you:
(function($){
$.fn.secondClass = function(){
var c = this.attr("class").split(" ");
if(c.length >= 2)
return c[1];
};
}(jQuery))
Usage: var class2 = $(selector).secondClass();
Hope this helps.

How do I select multiple classes incremented by 1 and their matching children?

I have multiple containers that I need to animate.
Basically: you click on class: box-n (e.g. box-1) and you slideToggle: box-child-n (e.g. box-child-1).
Instead of a click function for every box-n to toggle box-child-n, I want a simple line of code that matches box-n with its children class.
html:
<div class="box-1">Some clickable container</div>
<div class="box-child-1">This should toggle when box-1 is clicked</div>
<div class="box-2">Some clickable container</div>
<div class="box-child-2">This should toggle when box-2 is clicked</div>
Et cetera...
current jquery:
$('.box-1').click(function() { $('.box-child-1').slideToggle() });
$('.box-2').click(function() { $('.box-child-2').slideToggle() });
Sort of desired jquery (allInt function is made up.):
var $n = allInt();
$('.box-' + n).click(function() {
$('.box-child-' + _n).slidetoggle() // local variable to inter alia .box-1
})
I can't seem to think of any solution, so I am asking for help once again.
I appreciate every suggestion you folks give me!
Here's one way to do it that allows for the elements to have other classes besides the ones that you're using to pair them up:
$('div[class*="box-"]').click(function() {
var c = this.className.match(/\bbox-\d+\b/);
if (c)
$('div.' + c[0].replace(/-/, '-child-')).slideToggle();
});
Demo: http://jsfiddle.net/6xM47/
That is, use the [name*=value] attribute contains selector to find any divs with a class attribute that has "box-" in it somewhere. Then when clicked extract the actual class and check that it matches the "box-n" pattern - this allows for multiple (unrelated) classes on the element. If it does match, find the associated "box-child-n" element and toggle it.
Having said all that, I'd suggest structuring the markup more like this:
<div data-child="box-child-1">Some clickable container</div>
<div class="box-child-1">This should toggle when box-1 is clicked</div>
...because then the JS is simple and direct:
$('div[data-child]').click(function() {
$('div.' + $(this).attr('data-child')).slideToggle();
});
Demo: http://jsfiddle.net/6xM47/1/
To just answer your question, this will do the trick :
$("div[class^='box-']").click(function(){
$(this).parent().find('.' + $(this).attr('class').replace('-','-child-') ).slideToggle();
});
jsfiddle here.
Anyway i dont think you use a good approach (you may wrap child into parent div or use ids).

selecting on dom parser using jquery with relevant class div12 div31 all at one time

Thanks for reading my post..
Just consider the below scenario of html architecture.
<div class="wrapper">
<div class="doubt-123232" id="value"></div>
<div class="question></div>
<div class="doubt-232323" id="query"></div>
</div>
In the above DOM if you need to select the class starting with doubt-***** (which include doubt-123232, doubt-232323) all at a time and do processing using jQuery.
We can select each class one by one and do processing, but in my page I have lot like this . I cant do it for each class to select and do processing then it became a trivial process.
Is there way to select the similar class or id all at time for processing in jQuery?
Thanks.
Yes, you can do this using Attribute Starts With Selector:
var divs = $('div[class^="doubt-"]');
You can use:
var items = $('div[class^=doubt]');
This is known as the "starts with" selector.
Alternatively you could use:
var items = $('div[class*=doubt]');
which is the "contains" selector.
Note that in this case, doubt is one word. If there are multiple words with spaces in between, you should put quotes around them. It is not required to quote single words.
See here for documentation on the "starts with" selector.
You can use Attribute Starts With Selector [name^="value"]
var divs = $('div[class^="doubt-"]');
selecting them all:
var doubts= $('[class^="doubt-"]');
then you access them:
doubts.each(function(index){
this. ... // and so on
});
Try somthing like this:
$("[class^=doubt-]").each(function(){ //do some staff });

Counting div's with class and returning position

I have a page with many dynamically creted div's as seen below:
<div class="open"></div>
<div class="open"></div>
<div class="open"></div>
<div class="open"></div>
I'm looking for a way to get get a position of an element (eg. If the element is the first instance of, assign id="1" if element is the second instance of, assign id="2".
I'm currently using the following jquery, but am stuck, as Im not sure where to go from here.
$(document).ready(function () {
var numDialogs = $('.open').length;
});
Any suggestions?
Just use:
$('div.open').prop('id', function(i){
return 'openElement' + (i + 1);
});
JS Fiddle demo.
I've deliberately added a prefix string because while numerical ids are valid under HTML5, they remain invalid under HTML4, and are difficult to select using CSS selectors.
References:
prop().
Mark, you can target the element and then add an attribute like so:
$('.open').attr('id', numDialogs);
This will give it all 4's in this case, but I'll leave you to wrestle with the actual logic to implement the right numbers. Good luck.

jQuery CSS Selector combined with "this"

I'm trying to figure out if something like this would be possible. We are given that HTML structure
<a href='#' class='anyLink'>
<!-- here goes some content-->
<div class='childElement'><!-- here goes some content--></div>
</a>
I am not able to use ID's because there are many links and it's not defined how many more are to come. So my question is, do you guys know a way where I can do something like this :
$('a').on("click",function(e){
$(this +"div").val(); // for example.
});
I want to select a children element of that anchor that has been clicked or want to get the value of the children element. I also don't have any ID's of the children elements and I am trying to select things via CSS Selectors as td:nth-child(4).
Could anybody tell me if this is possible ?
try
$('a').on("click",function(e){
$("div",this).text(); // for example.
});
$('a').on("click",function(e){
$(this).children("div").eq(0).html();
});
You are looking for a function called .children().
But you can also try something like this:
$('a').on('click', function( e ) {
$('div', this).val(); // Each div child of this element
$(this).children('div'); // Each div child of this element
});

Categories