Select by next instance of class with jQuery - javascript

I'm looking to convert a function that selects by id to select the next instance of a given class.
Here is the code.
function swap3(oldDivId, newDivId) {
var oldDiv = document.getElementById(oldDivId);
var newDiv = document.getElementById(newDivId);
oldDiv.style.display = "none";
newDiv.style.display = "block";
}

Suppose you have this HTML:
<div id="test"></div>
<img>
<br>
<div></div>
<input>
<div class="abc">Found it</div>
<div class="cdf"></div>
Updated at 2021
The original answer is quite old now. Since the original question have the jQuery tag, the answer keeps valid and usable. But for those coming here with the hope to see an updated JavaScript code with no dependency on jQuery, take a look on how querySelector is a awesome nowadays:
const next = document.querySelector('#test ~ .abc')
next.textContent = 'Yeah, you found it!'
So the secret is to use the general sibling combinator that matches all iterations of the second element, but with querySelector that returns only the first match.
Original answer
So you select the first div by id:
var some = $("#test");
Then you want to find the next div with the class abc:
var next = some.nextAll("div.abc");
Suppose you want a variable as the className:
var x = "abc";
var next = some.nextAll("div." + x);

If I understand your question:
function nextItem(className) {
return $('#ID').closest('.' + className);
}
using closest: http://api.jquery.com/closest/

Select by ID in jQuery:
$('#class_name')
Select by class in jQuery:
$('.class_name')
Get the next item in jQuery:
$('.class_name').next('.class_name')
Using this, you can do something like
// Something to remember the current element
var currentElement = false;
function getNext(className)
{
// First time, there will be no current element
if (!currentElement)
{
currentElement = $('.' + className);
return currentElement;
}
// Other times...
currentElement = $(currentElement).next('.' + className);
return currentElement;

Related

JavaScript | appendChild to all classes

I have problem with append Child to whole classes in my document which the name of class is "onbackorder". Here is my code:
<script>
var first = document.createElement("p");
var text = document.createTextNode("On backorder");
first.appendChild(text);
var isRequestQuote = document.getElementsByClassName('onbackorder');
if (isRequestQuote.length > 0) {
document.querySelector(".onbackorder").appendChild(first);
}
</script>
For this moment function put selector randomly. How can I get same selector in whole document where class is "onbackorder".
Thank you
There are 2 points:
document.querySelector(".onbackorder") is just return first item. So you need to use document.querySelectorAll('.onbackorder').
The Document method querySelector() returns the first Element within
the document that matches the specified selector, or group of
selectors. If no matches are found, null is returned.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
var first = document.createElement("p"); you have to create multiple reference variable to append to each onbackorder item. Because you cannot create only one and append to multiple items.
So I modified your code and make it works. You can check it at below:
var first = document.createElement("p");
var text = document.createTextNode("On backorder");
first.appendChild(text);
const allBackOrders = document.querySelectorAll('.onbackorder');
allBackOrders.forEach((item) => {
var newItem = first.cloneNode(true);
item.appendChild(newItem);
});
<div class="onbackorder"></div>
<div class="onbackorder"></div>
<div class="onbackorder"></div>

Change existing DIV from a CLASS to an ID

Is this possible? Or is there a way to tack on and ID to an existing div?
This is my code. I can't get the code to work using classes, but I found when I used getElementById and changed the div to an ID, that it did. But I have a ton of already posted stuff so it would take forever to go through all those posts and change it manually to an ID.
Can I incorperate JQuery in this and still have it work? I tried that with something I stumbled across but it didn't work so I removed it. I don't remember what it is now though. :S
<div id="imdb" class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnum = document.getElementsByClassName("imdb");
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnum + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
window.onload = imdbdiv();
</script>
Can anyone help. I cannot for the life of me figure this out.
JsFiddle
Your problem was, you were appending the collection returned by document.getElementsByClassName instead of looping through the elements in the collection. You can verify this by looking at the href property of the link in your jsFiddle. You must loop through the values, then access the data in their innerHTML property.
You can use document.querySelectorAll to get a list of all elements matching a certain CSS selector, in your case .imdb. This is more flexible, in case you want to select elements with more than one class. I've pasted the code from the updated jsFiddle below.
function imdbdiv() {
var imdbMain = "http://www.imdb.com/title/",
end = "/#overview-top",
imdbValueDivs = document.querySelectorAll('.imdb'),
length = imdbValueDivs.length,
// Iterator values
i,
newDiv,
newLink;
// Loop over all of your link value containers
for (i = 0; i < length; i++) {
// Create the container
newDiv = document.createElement('div');
// Create the new link
newLink = document.createElement('a');
newLink.href = imdbMain + imdbValueDivs[i].innerHTML + end;
newLink.innerHTML = "My favorite film";
// Add the link to the container,
// and add the container to the body
newDiv.appendChild(newLink);
document.body.appendChild(newDiv);
}
}
window.onload = imdbdiv();
If you have many such divs on your page, then it could be like this:
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnums = document.getElementsByClassName("imdb");
for (var i =0; i < idnums.length; i++) {
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnums[i].innerText + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
}
window.onload = imdbdiv();
</script>
See jsfiddle
UPDATE:
The following string was incorrect:
window.onload = imdbdiv;
Okay, so your question is a little bit unclear.
The way I understood your question is that you have a whole bunch of div elements with class attribute and what you want is to simply copy the class value to the id attribute of the div elements.
If that's correct then try something like this with jquery:
<script>
$(document).ready(function(){
$(".imdb").each(function(imdbDiv){
var classValue = imdbDiv.attr("class");
imdbDiv.attr("id", classValue);
});
});
</script>

Access dynamic generated div id

I have some div ids that are generated dynamicly via php
<div id='a<?php echo $gid?>>
How can I access them in JavaScript? All these divs start with "A" followed by a number.
Is there some kind of search function
getElementById(a*)?
Thanks for any help
No generic JavaScript function for this (at least not something cross browser), but you can use the .getElementsByTagName and iterate the result:
var arrDivs = document.getElementsByTagName("div");
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = arrDivs[i];
if (oDiv.id && oDiv.id.substr(0, 1) == "a") {
//found a matching div!
}
}
This is the most low level you can get so you won't have to worry about old browsers, new browsers or future browsers.
To wrap this into a neater function, you can have:
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
The usage example would be:
window.onload = function() {
var arrDivs = GetElementsStartingWith("div", "a");
for (var i = 0; i < arrDivs.length; i++) {
arrDivs[i].style.backgroundColor = "red";
}
};
Live test case.
In case you choose to use jQuery at some point (not worth for this thing alone) all the above code turns to single line:
$(document).ready(function() {
$('div[id^="a"]').css("background-color", "blue");
});
Updated fiddle, with jQuery.
No, you need a fixed id value for getElementById to work. However, there are other ways to search the DOM for elements (e.g. by CSS classes).
You can use querySelectorAll to get all divs that have an ID starting with a. Then check each one to see if it contains a number.
var aDivs = document.querySelectorAll('div[id^="a"]');
for(var index = 0, len = aDivs.length; index < len; index++){
var aDiv = aDivs[index];
if(aDiv.id.match(/a\d+/)){
// aDiv is a matching div
}
}​
DEMO: http://jsfiddle.net/NTICompass/VaTMe/2/
Well, I question myself why you would need to select/get an element, that has a random ID. I would assume, you want to do something with every div that has a random ID (like arranging or resizing them).
In that case -> give your elements a class like "myGeneratedDivs" with the random ID (if you need it for something).
And then select all with javascript
var filteredResults=document.querySelectorAll(".myGeneratedDivs").filter(function(elem){
....
return true;
});
or use jQuery/Zepto/YourWeaponOfChoice
var filteredResults=$(".myGeneratedDivs").filter(function(index){
var elem=this;
....
return true;
});
If you plan to use jQuery, you can use following jQuery selectors
div[id^="a"]
or
$('div[id^="id"]').each(function(){
// your stuff here
});
You will have to target the parent div and when someone click on child div inside a parent div then you can catch the child div.
<div id="target">
<div id="tag1" >tag1</div>
<div id="tag1" >tag2</div>
<div id="tag1" >tag3</div>
</div>
$("#target").on("click", "div", function() {
var showid = $(this).attr('id');
alert(showid)
});
getElementById() will return the exact element specified. There are many javascript frameworks including jQuery that allow much more powerful selection capabilities. eg:
Select an element by id: $("#theId")
Select a group of elements by class: $(".class")
Select subelements: $("ul a.action")
For your specific problem you could easily construct the appropriate selector.

Take <span> class and put in <a> attribute jquery

I have html like this.
<span class="gallery-open-item year-icon-Yes 2010">
<a href="/year/none">
</a>
</span>
I need to check using jQuery if span.gallery-open-item has year-icon-Yes class, and if so take the next (for this example is 2010) class and place it in the href attribute like this:
<a href="/year/2010"/>
All this I need in jQuery or JavaScript.
I have done some experiments but I can't take 2010 to normal javascript variable.
Any ideas?
Sorry for my English.
Here's another approach. Tested, working.
$('.gallery-open-item.year-icon-Yes').each(function(){
that = this;
var classes = $(this).attr('class').split(' ');
$.each(classes, function(i, val) {
if (val.match(/^y-/gi)) {
$('a', that).attr('href', function(){
return this.href.replace('none', val.split('-')[1]);
});
}
});
});
Assumes this markup:
<span class="gallery-open-item year-icon-Yes y-2010">
<a href="/year/none/">
Test
</a>
</span>
How about this:
$('span.gallery-open-item.year-icon-Yes > a').each(function(i, elem) {
$.each($(elem).parent().attr('class').split(' '), function(j, klass) {
// NOTE: use /^y-([\d]*)$/ if years are prefixed with y-
if (year = klass.match(/^([\d]*)$/))
$(elem).attr('href', $(elem).attr('href').replace('none', year[1]));
});
});
This would iterate over every A tag beneath your SPAN tags and fetch the classes from each parent, search these for a number and replace the "next" part.
Update: Added comments for the case you switch to prefixed years.
Update 2: Now tested and working (using Prototype usually *sigh*).
Here's one way of doing it. First, we select the span tags that have both the classes gallery-open-item and year-icon-Yes. Then, for each of them we're going to get an array of classes that the span tag has. I loop over the class names, and check for the first one that is a number. Finally, modify the a tag inside the span to set the desired url.
$(document).ready(function() {
$('span.gallery-open-item.year-icon-Yes').each(function() {
var classNames = $(this).attr('class').split(' ');
for (var i = 0; i < classNames.length; i++)
{
if (!isNaN(classNames[i]))
{
var year = classNames[i];
$(this).find('a').attr('href', '/year/'+year);
break;
}
}
});
});
Edit: Based on the comments that class names should not start with a number, it's pretty easy to make this work for class names of the form y-xxxx:
$(document).ready(function() {
$('span.gallery-open-item.year-icon-Yes').each(function() {
var classNames = $(this).attr('class').split(' ');
for (var i = 0; i < classNames.length; i++) {
var year = classNames[i].substring(2);
if (!isNaN(year)) {
$(this).find('a').attr('href', '/year/' + year);
break;
}
}
});
});

How to get all elements inside "div" that starts with a known text

I have a div element in an HTML document.
I would like to extract all elements inside this div with id attributes starting with a known string (e.g. "q17_").
How can I achieve this using JavaScript ?
If needed, for simplicity, I can assume that all elements inside the div are of type input or select.
var matches = [];
var searchEles = document.getElementById("myDiv").children;
for(var i = 0; i < searchEles.length; i++) {
if(searchEles[i].tagName == 'SELECT' || searchEles.tagName == 'INPUT') {
if(searchEles[i].id.indexOf('q1_') == 0) {
matches.push(searchEles[i]);
}
}
}
Once again, I strongly suggest jQuery for such tasks:
$("#myDiv :input").hide(); // :input matches all input elements, including selects
Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :
var elements = document.getElementById('parentContainer').children;
Option 2: Likely slowest :
var elements = document.getElementById('parentContainer').getElementsByTagName('*');
Option 3: Requires change to code (wrap a form instead of a div around it) :
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;
var matches = [];
for (var i = 0; i < elements.length; i++)
if (elements[i].value.indexOf('q17_') == 0)
matches.push(elements[i]);
With modern browsers, this is easy without jQuery:
document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');
The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^= which means "starts with".
Note that all browsers released since June 2009 support this.
Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:
function fillArray(vector1,vector2){
for (var i = 0; i < vector1.length; i++){
if (vector1[i].id.indexOf('q17_') == 0)
vector2.push(vector1[i]);
if(vector1[i].tagName == 'DIV')
fillArray (document.getElementById(vector1[i].id).children,vector2);
}
}
function selectAllElementsInsideDiv(divId){
var matches = new Array();
var searchEles = document.getElementById(divId).children;
fillArray(searchEles,matches);
return matches;
}
Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:
var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv = selectAllElementsInsideDiv('myDiv')
I have tested it and it worked for me. I hope it helps you.
var $list = $('#divname input[id^="q17_"]'); // get all input controls with id q17_
// once you have $list you can do whatever you want
var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {
var id = $(this).prop("id"); // get id
var cbx = '';
if ($(this).is(':checkbox') || $(this).is(':radio')) {
// Need to see if this control is checked
}
else {
// Nope, not a checked control - so do something else
}
});
i have tested a sample and i would like to share this sample and i am sure it's quite help full.
I have done all thing in body, first creating an structure there on click of button you will call a
function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens.
I have given alerts here on different level so u can test where r u now in the coding .
<body>
<h1>javascript to count the number of children of given child</h1>
<div id="count">
<span>a</span>
<span>s</span>
<span>d</span>
<span>ff</span>
<div>fsds</div>
<p>fffff</p>
</div>
<button type="button" onclick="selectallelement('count')">click</button>
<p>total element no.</p>
<p id="sho">here</p>
<script>
function selectallelement(divid)
{
alert(divid);
var ele = document.getElementById(divid).children;
var match = new Array();
var i = fillArray(ele,match);
alert(i);
document.getElementById('sho').innerHTML = i;
}
function fillArray(e1,a1)
{
alert("we are here");
for(var i =0;i<e1.length;i++)
{
if(e1[i].id.indexOf('count') == 0)
a1.push(e1[i]);
}
return i;
}
</script>
</body>
USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS

Categories