I have a javascript code that retrieves an id from a CollectionType Symfony:
$(document).ready(function() {
$('.well').change(function () {
var day_n = document.getElementById('command_billet_billet_0_dateBirthday_day').value;
var month_n =
document.getElementById('command_billet_billet_0_dateBirthday_month').value;
var year_n =
document.getElementById('command_billet_billet_0_dateBirthday_year').value;
Each time a new form is added, this id will become
document.getElementById('command_billet_billet_1_dateBirthday_day').value;
document.getElementById('command_billet_billet_1_dateBirthday_month').value;
document.getElementById('command_billet_billet_1_dateBirthday_year').value;
document.getElementById('command_billet_billet_2_dateBirthday_day').value;
document.getElementById('command_billet_billet_2_dateBirthday_month').value;
document.getElementById('command_billet_billet_2_dateBirthday_year').value;
the number changes and the end of id (day, month, year)
Is it possible to integrate javascript code inside getElementById to get all the numbers and make the distinction of the end of id ?
document.querySelectorAll() could do it.
var ps = document.querySelectorAll('[id^=id]');
console.log(ps);
for(i in ps){
ps[i].style.color = 'red';
}
<p id="id1A">Hello</p>
<p id="id2A">World</p>
<p id="id3A">Hello!</p>
Logic
Fetch all elements using generic selector
Loop over them and get ID
Now use a regex or any other string manipulator to get number.
Sample
(function(){
var digitReg = /\d+/;
var wells = document.querySelectorAll('.well');
for(var i = 0; i< wells.length; i++){
var id = wells[i].getAttribute('id');
console.log(id.match(digitReg)[0])
}
})()
<div class="well" id="command_billet_billet_1_dateBirthday_day"></div>
<div class="well" id="command_billet_billet_2_dateBirthday_day"></div>
If you can change your html markup then you can use jQuery data() api
Like this :
$(function() {
$("#getIds").click(function() {
var ids = [];
$(".well").each(function() {
ids.push($(this).data("id"));
})
console.log(ids);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well" data-id="1"> div Id 1</div>
<div class="well" data-id="2"> div Id 2</div>
<div class="well" data-id="3">div Id 3</div>
<div class="well" data-id="4"> div Id 4</div>
<div class="well" data-id="5">div Id 5</div>
<div class="well" data-id="6">div Id 6</div>
<button id="getIds" type="button">Get Ids</button>
Related
I'm trying to have js change the title attributes for each div based on each divs text content in html.
I want to add the title of each div from its own text, so for example: "Text Example 1"s title would be "Text Example 1", "Text Example 2"s title would be "Text Example 2" and so on.
Currently I've made a js code that does that but only for one of the divs. I'm a complete beginner in js so any advice is appreciated.
<div class="example">
<div class="text1" id="id-text1">Text Example 1</div>
</div>
<div class="example">
<div class="text1" id="id-text1">Text Example 2</div>
</div>
<div class="example">
<div class="text1" id="id-text1">Text Example 3</div>
</div>
const titleContent = document.getElementById("id-text1");
function ChangeTitle(){
document.querySelectorAll('.text1').forEach(function ChangeTitleSecond(){
titleContent.setAttribute('title', titleContent.textContent);
})
};
window.onload = ChangeTitle();
Steps to set title of <div> to it's (text) content:
Get all of the <div>s (selector is div.text1)
For each of them, set title to innerText value
Solution:
<div class="example">
<div class="text1">Text Example 1</div>
</div>
<div class="example">
<div class="text1">Text Example 2</div>
</div>
<div class="example">
<div class="text1">Text Example 3</div>
</div>
<script>
divs = Array.from(document.querySelectorAll("div.text1"))
for (elem of divs) {
elem.setAttribute("title", elem.innerText)
}
</script>
Demo
getElementById() returns only a single element. id attributes should be unique within the document. But that's ok, you don't need it. You're already getting a list of the elements to go through with querySelectorAll()
forEach() will pass each element as the first parameter of your function.
function ChangeTitle(){
document.querySelectorAll('.text1').forEach(function
ChangeTitleSecond(item){
item.setAttribute('title', item.textContent);
})
};
window.onload = ChangeTitle();
You can use this implementation. If you need a list of some items which has the same attributes (such as id, class or tag) you can pick them all through their specific attribute of them by querySelectorAll.
const titleContentList = document.querySelectorAll('[id=id-text1]')
function ChangeTitle(){
titleContentList.forEach((item)=>{
const title = item.textContent
if(!title) return;
item.setAttribute('title',title)
})
}
window.onload = ChangeTitle();
i have this html collection, i want if i click on any div class ".sday"
any other div that are present after that be remove .
for example if we click on sday 2 we should keep sday1 and sday 2, and 3 and 4 must delete
my script removing count is ok but it delete wrong div.
any idea?
<div id="parent" class="parent">
<div class="room-sheet">
<div class="sday">1</div>
</div>
<div class="room-sheet">
<div class="sday">2</div>
</div>
<div class="room-sheet">
<div class="sday">3</div>
</div>
<div class="room-sheet">
<div class="sday">4</div>
</div>
</div>
script(using jquery)
<script>
$(".sday").click(function(){
console.log("hello");
var parentElement = $(this).parent().parent().find('.room-sheet');
var parentChildernCount = $(this).parent().parent().find('.room-sheet').length;
var elementIndex = $(this).closest('.room-sheet').index();
var dd = parentChildernCount - elementIndex;
for(let i=elementIndex; i < dd; i++){
//note: make sure any element after our index in deleted!!!
$("#parent").find('.room-sheet').children().eq(i).remove();
}
})
</script>
Listen for clicks on a .sday on the parent, navigate to the parent of the clicked .sday (a .room-sheet), call nextAll to get all subsequent siblings, and .remove() them:
$('#parent').on('click', '.sday', function() {
$(this).parent().nextAll().remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent" class="parent">
<div class="room-sheet">
<div class="sday">1</div>
</div>
<div class="room-sheet">
<div class="sday">2</div>
</div>
<div class="room-sheet">
<div class="sday">3</div>
</div>
<div class="room-sheet">
<div class="sday">4</div>
</div>
</div>
Also, there's no need to require a big library like jQuery for something this simple, you may implement this with native DOM methods, if you like:
document.querySelector('#parent').addEventListener('click', ({ target }) => {
if (!target.matches('.sday')) {
return;
}
const sheet = target.parentElement;
while (sheet.nextSibling) {
sheet.nextSibling.remove();
}
});
<div id="parent" class="parent">
<div class="room-sheet">
<div class="sday">1</div>
</div>
<div class="room-sheet">
<div class="sday">2</div>
</div>
<div class="room-sheet">
<div class="sday">3</div>
</div>
<div class="room-sheet">
<div class="sday">4</div>
</div>
</div>
Save the current number and the maximum number in variables then just iterate through them, making sure not to delete the clicked one:
$(".sday").on("click", function() {
let start = parseInt($(this).text());
let finish = parseInt($(".sday").last().text());
for (let i = start + 1; i <= finish; i++) {
$(`.sday:conatins(${i})`).remove();
}
});
Assume I have 2 groups of divs -- both with click buttons, which when clicked, it will change the text content of the child within that group.
How can I accomplish that with pure javascript?
Thanks in advance
HTML
<div class="parent">
<button>Click</button>
<div class="child">Test1</div>
<div class="child">Test4</div>
</div>
<div class="parent">
<button>Click</button>
<div class="child">Test2</div>
<div class="child">Test5</div>
</div>
Javascript
var button = document.querySelectorAll("button");
for(i = 0; i < button.length; i++){
button[i].addEventListener("click", function(){
var parent = document.querySelectorAll(".parent");
var child = parent.querySelector(".child:nth-child(2)");
this.child.textContent = "success"; //just made up to show what I'm trying to accomplish
});
}
Assuming that you want to change only the first div element inside parent, here's one approach:
var button = document.getElementsByTagName("button");
Array.from(button).forEach(v => v.addEventListener('click', function() {
this.parentNode.children[1].innerHTML = 'success';
}));
<div class="parent">
<button>Click</button>
<div class="child">Test1</div>
<div class="child">Test4</div>
</div>
<div class="parent">
<button>Click</button>
<div class="child">Test2</div>
<div class="child">Test5</div>
</div>
Simply use the this keyword to figure out which button is clicked, then get its .parentNode and afterwards its .children, select the second one ([1]) and change the text, like so:
var button = document.querySelectorAll("button");
for(i=0; i < button.length; i++) {
button[i].addEventListener("click", function() {
this.parentNode.children[1].innerHTML = 'success';
});
}
<div class="parent">
<button>Click</button>
<div class="child">Test1</div>
<div class="child">Test4</div>
</div>
<div class="parent">
<button>Click</button>
<div class="child">Test2</div>
<div class="child">Test5</div>
</div>
I want to traverse through pages and toggle active class through them. How should I do this without using set class?
HTML
<div class="page active"></div>
<div class="set">
<div class="page"></div>
<div class="page"></div>
</div>
<div class="page"></div>
jQuery
$('.active').toggleClass('active').toggle().nextAll('.page').toggleClass('active');
I am assuming that by "traverse" you mean you want to toggle the .page divs one by one in a certain order.
If that is the case, write an algorithm that traverses a tree: given a root, toggle if it is a .page, and recursively deal with each of its children
function traverse(root){
if(!root) return;
if(root.hasClass('page')) root.toggle('active');
root.children().forEach(function(child){
traverse(child);
});
//lets say you want to bind to click event on every div
$('div').click(function(){
traverse($(this));
});
}
Unfortunately we don't have a direct way to find the next non sibling element, but we can handle that situation in many ways using jquery functions. I just tried on way to achieve your goal, check out this working fiddle and let me know if you need any clarity, added some inline comments also for your understanding.
HTML:
<div class="page active">div 1</div>
<div class="page">div 2</div>
<div class="set">
<div class="page">set 1 - div 1</div>
<div class="page">set 1 - div 2</div>
<div class="page">set 1 - div 3</div>
</div>
<div class="page">div 5</div>
<div class="set">
<div class="page">set 2 - div 1</div>
<div class="page">set 2 - div 2</div>
</div>
<div class="page">div 6</div>
<button class="next-btn">Next</button>
CSS:
.active {
color: red;
}
.next-btn {
cursor: pointer;
}
Javascript:
$(function() {
$('button').click(function() {
var elem = $(".page.active").toggleClass('active'); // current active element
var nextElem = elem.next(); // next element
// go above one level and get next element
// if no next element exists, means end of the child level
if (!nextElem.length) {
nextElem = elem.parent().next();
}
// if next element has some PAGE children then update the first child element
if (nextElem.children('.page').length > 0 ) {
nextElem.children('.page:first-child').toggleClass('active');
} else if (nextElem.hasClass('page')) {
nextElem.toggleClass('active');
}
});
});
This approach handles the scenario with one child level, you can extend this to multiple levels also with recursive functions, I think this helps you to handle your scenario accordingly.
Working fiddle
You could achieve that using indexes to get the next element in the DOM using the index of active one +1 then active it, I think the following is what you are looking for:
var getActiveIndex = function(){
var active_index;
$('.page').each(function(i){
if ( $(this).hasClass('active') )
active_index = i;
})
return active_index;
}
$('body').on('click', '.next', function(){
var active_page_index = getActiveIndex(); //Get active page index
var new_index = active_page_index+1; //Set the next page index
var next_page = $('.page:eq('+new_index+')'); //Get the next page
$('.page').removeClass('active');
if(next_page.length)
next_page.addClass('active');
else
$('.page:first').addClass('active');
})
I hope this helps.
var getActiveIndex = function(){
var active_index;
$('.page').each(function(i){
if ( $(this).hasClass('active') )
active_index = i;
})
return active_index;
}
$('body').on('click', '.next', function(){
var active_page_index=getActiveIndex();
var new_index = active_page_index+1;
var next_page = $('.page:eq('+new_index+')');
$('.page').removeClass('active');
if(next_page.length)
next_page.addClass('active');
else
$('.page:first').addClass('active');
})
.active{
background-color: red;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page active">page</div>
<div class="set">
<div class="page">- Set page</div>
<div class="page">- Set page</div>
</div>
<div class="page">page</div>
<div class="page">page</div>
<div class="page">page</div>
<div class="set">
<div class="page">- Set page</div>
<div class="page">- Set page</div>
</div>
<div class="page">page</div>
<br>
<button class='next'>Active the next page</button>
I am trying to use jQuery to get the value of the divs with the classes of more_details_con, more_details_desc and more_details_res and when edit_entry is clicked but I don't think I am traversing the DOM correctly because the alert just says undefined.
The HTML
<div class="details">
<span class="id">1234</span>
<span class="contact">account name</span>
</div>
<div class = "more_details">
<div class = "more_details_btns">
<div class="go_account">Go to Account</div>
<div class="edit_entry">Edit</div>
<div class="delete_entry">Delete</div>
</div>
<div class="container">
<div class="more_details_title">Contact:</div>
<div class="more_details_con">Contact name</div>
<p class="clear"></p>
</div>
<div class="container">
<div class="more_details_title">Description:</div>
<div class="more_details_desc">Actual Description</div>
<p class="clear">
</div>
<div class="container">
<div class="more_details_title">Resolution:</div>
<div class="more_details_res">Actual Resolution</div>
<p class="clear">
</div>
</div>
The jQuery I've tried
$("#results").on("click", ".edit_entry", function() {
var contact = $(this).next(".more_details_con").html();
var desc = $(this).next(".more_details_desc").html();
var res = $(this).next(".more_details_res").html();
alert(contact+desc+res);
});
The issue is because the elements you're looking for are not siblings of the one which raised the event. You instead could use closest() to find the nearest common parent element, .more_details, and then find() to get the element you want. Try this:
$("#results").on("click", ".edit_entry", function() {
var $parent = $(this).closest('.more_details');
var contact = $parent.find(".more_details_con").text();
var desc = $parent.find(".more_details_desc").text();
var res = $parent.find(".more_details_res").text();
console.log(contact, desc, res);
});