<div id="abc">
<div id="a_b"> abcd </div>
<div id="c_d"> xyz </div>
</div>
Problem is the divs are dynamically generated and their IDs keep changing every time the page is rendered. On window load, the contents of a_b and c_d has to be passed a function func() and the output should be placed within the same div. How can I grab each child of div abc and modify their contents?
Try to use .text() along with .each() to achieve what you want.
$(window).load(function(){
$("#abc > div").each(function() {
$(this).text(someFunction($(this).text()));
});
});
Or the better code would be using the receiver function of .text(),
$(window).load(function(){
$("#abc > div").text(function(_,v) {
return someFunc(v);
});
});
Given that the #abc div is always available, you can select that and then any direct child div element and loop over them by using text() with a handler function, like this:
$('#abc > div').text(function(i, v) {
return v + ' foobar';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="abc">
<div id="a_b">abcd</div>
<div id="c_d">xyz</div>
</div>
Alternatively you can create an array of the content of the child divs and pass that to your func():
var textContents = $('#abc > div').map(function() {
return $(this).text();
}).get();
func(textContents);
function func(arrText) {
console.log(arrText); // = [ 'abcd', 'xyz' ]
}
Related
Is there a way to assign nested div attribute with variable? Like
<div>
<div>
123456
</div>
</div>
Become
<div>
<div sectionid="123">
123456
</div>
</div>
BTW above component will be created by JavaScript.
I've tried something like this, but it didn't work.
var a = $('<div><div>123456</div></div>');
a.eq(":nth-child(2)").attr("sectionid", "123");
Try this snippet.
//FOR DOM HTML
console.log("FOR DOM HTML");
//1st way
$('#input > div').find('div').attr("sectionid","123");
console.log($('#input').html());
//2nd way
$('#input > div > div').attr("sectionid","321");
console.log($('#input').html());
//JS HTML
console.log("FOR JS OBJECT");
var input = $('<div><div>123456</div></div>');
//1st way
input.eq(0).children().attr('sectionid', '456');
console.log(input[0].outerHTML);
var input = $('<div><div>123456</div></div>');
//2nd way
$(input[0]).children().attr('sectionid', '789');
console.log(input[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input">
<div>
<div>
123456
</div>
</div>
</div>
nth-child(2) maches elements that are the second child element of their parent. This is not the case for your div, it is the first element of the parent div.
.eq finds an element at a specific index. It is not the place to pass a selector.
The child selector, >, will find a child element, i.e. div>div will find a div that is an immediate child of a div.
Note that the code you've provided, $('<div></div>123456<div></div>');, doesn't create a DOM tree like the one you've pasted.
Update, now that the code is edited, the value of a is a div with a child div. Since a.find will perform a search within a, you don't have to use a child selector, but can find the div immediately:
a.find('div')
Just apply attribute to children. No complicated 'find', eq(), etc.
var a = $('<div><div>123456</div></div>');
a.children().attr('sectionid', '123');
$('body').append(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Why don't you add it in the first place? Not clear if you add it later!
$(document).ready(function() {
var sectionid = "123";
var a = $('<div><div sectionid="' + sectionid + '">123456</div></div>');
$('body').append(a);
});
div[sectionid]{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this - I have added comments to the code to explain what is happening.
Inspect the element to see that the attribute is added
var a = $('<div><div>123456</div></div>'); // change this to match the structure you want
a.children() // .children gets the direct descendant (which should be the nested div
.eq(0) // gets the first in the array that is returned (if there are multiple direct descendents) - it is a 0 based index selector
.attr('sectionid', '123');
$('body').append(a)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
More information about .children()
More information about .eq()
try it :
$(document).ready(function(){
$("div").eq(1).attr("sectionid","123");
})
I just want to ask let say if we have multiple divs with same id how can we display none them using javascript ?
I tried:
<script>
function filterfunc() {
if(document.getElementById('filter_deductible').value == 'id_50'){
document.getElementById('id_0').style.display = 'none';
document.getElementById('id_50').style.display = 'block';
}
}
</script>
And here is my html divs with same ids:
<div id="id_0">0</div>
<div id="id_0">0</div>
<div id="id_50">50</div>
But its hidding only one div of id id_0 instead of all div having id_0
Any suggestions please
Id must be unique, you should use class like,
<div class="id_0">0</div>
<div class="id_0">0</div>
<div class="id_50">50</div>
And to hide all id_0 use
function filterfunc() {
if($('#filter_deductible').val() == 'id_50'){
$('div.id_0').hide();
$('div.id_50').show();
}
}
It simple using jQuery like
HTML
<select name="filter_deductible" id="filter_deductible">
<option value="id_0">0</option>
<option value="id_50">50</option>
</select>
<div id="id_0">0</div>
<div id="id_0">0</div>
<div id="id_50">50</div>
jQuery
$("#filter_deductible").change(function(){
if($(this).val()=="id_50")
{
$('[id="id_0"]').hide();
}
});
Demo
you should use a class in case there are multiple elements. Or use different ids.
Ids are meant to be unique.
<script>
function filterfunc() {
if(document.getElementById('filter_deductible').value == 'id_50'){
$('.id_0').css("display","none")
$('.id_50').css("display","block")
}
}
</script>
<div class="id_0">0</div>
<div class="id_0">0</div>
<div class="id_50">50</div>
Or
<script>
function filterfunc() {
if(document.getElementById('filter_deductible').value == 'id_50'){
$('.id_0').hide()
$('.id_50').css("display","block")
}
}
</script>
<div class="id_0">0</div>
<div class="id_0">0</div>
<div class="id_50">50</div>
Do not do this. Having multiple elements with the same ids leads to undefined behaviour. If you need to attach information to your dome nodes use data attributes or classes.
Notice how getElementById is singular form? It only ever expects to select and return one element.
That being said, you can probably get away with
document.querySelectorAll("#id_0")
if you want to use javascript functions on dom elements you have to use class not id attribute.
id attribute is unique in whole html document.
try to use jquery.
$.(document).ready(function(){
$("#filter_deductible").change(function(){
var $this = $(this); //instance of element where was changed value
if($this.val() == 'id_50'){
$(".id_0").hide();
$(".id_50").show();
}
});
});
your document html should looks like.
<div class="id_0">0</div>
<div class="id_0">0</div>
<div class="id_50">50</div>
this will works only if you will include jquery library inside tags. And your dom element #filter_deductible allows change event trigger.
hope i helped you
Use classes in this case ID is unique.
<div class="zero">0</div>
<div class="zero">0</div>
<div class="class_50">50</div>
you can use jQuery:
$('.zero').hide();
$('.class_50').show();
The HTML spec requires that the ID attribute to be unique in a page:
If you want to have several elements with the same ID your code will not work as the method getElementByID only ever returns one value and ID's need to be unique. If you have two ID's with the same value then your HTML is invalid.
What you would want to do is use div class="id_0" and use the method getElementsByClassName as this returns an Array of elements
function filterFunc() {
var n = document.getElementsByClassName("id_0");
var a = [];
var i;
while(n) {
// Do whatever you want to do with the Element
// This returns as many Elements that exist with this class name so `enter code here`you can set each value as visible.
}
}
$EACH DEMO
anyhow iam getting the text of "div class": and printing in console.,
and iam trying to append the same text in "li > button", which is not happening, not sure where iam going wrong,
html :
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
JS:
//step - 1
$.each($('.productDescription'), function() {
var classTxt = $(this).text();
console.log(classTxt);
});
//outputs: Red Orange Green
//step - 2 now im trying to append the text to li
var liBtn = $(this).find('li').next('button');
console.log("Text of Button - "+ classTxt);
console.log(liBtn)
for (var i = liBtn.length; i >= 0; i++) {
liBtn[i]
};
Appreciate Your Help, Thanks
There are several errors in your code. classTxt is undefined outside of the each handler's context and the second this refers to window object and not to the .productDescription elements.
I'd suggest using the .append() method's callback function:
// cache the collection for better performance
var $p = $('.productDescription');
$('li button').append(function (index) {
return $p.eq(index).text();
});
http://jsfiddle.net/46yo7etz/
You could also use the .text() method:
$('li button').text(function(index, currentTextContent) {
// using indices for selecting
// the corresponding `.productDescription` element
return currentTextContent + $p.eq(index).text();
});
Please note that your fiddle's markup is invalid. li element should be child of an ul/ol element.
$('li > button').text(function() {
return $('.productDescription').eq( $('li > button').index( this ) ).text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
$("button").each(function(i){
$(this).text( $(".productDescription").eq(i).text() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<ul>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
</ul>
http://jsfiddle.net/simply_simpy/uqmpvb7e/
<div class="abc">
<a><img></a>
<h4></h4>
<div class="xyz">
Hello
</div>
</div>
in above html code how do i check whether div having class abc has div having class xyz.
You can simply do this:
var list = document.querySelectorAll('div.abc div.xyz');
if (1 == list.length) {
alert("found");
}
Here's a demo: http://jsfiddle.net/3xQ5X/
Using JQuery:
$("div.abc").has("div.xyz");
Try something like this:
Get your parent div an id like abc.
var v = document.getElementById('abc');
for(var i in v.children)
{
if( v.children[i].nodeName == 'DIV')//this will tell if the parent div has children divs
{
console.log(v.children[i].className == 'xyz');//this will be true if the child div has a class named xyz.
}
}
Also remember to modify this script according to your requirement. I mean you can give an specific class in place of id to the divs you want to traverse. To select all the divs containing some specific class, use this link's function.
This script will do the needful.
<script type="text/javascript">
$(document).ready(function(){
if($("div.abc").children('div').hasClass("xyz"))
{
alert("found");
}
});
</script>
For example I have simple html.
<body>
<div class="a">
<div class="child"></div> <!-- div element I click -->
<div class="childINeedToSelect"></div> <!-- div element I need to be selected -->
<div class="child"></div>
</div>
<div class="a">
<div class="child"></div>
<div class="childINeedToSelect"></div>
<div class="child"></div>
</div>
</body>
When I click on top first child class div I need to change, for example, border ONLY of the first childINeedToSelect class div. They have the same parent - a class div, but the difficult is that there are more than just one element with class a. I've already tried:
$(document).ready(function () {
var child = $('.child');
child.bind('click', function() {
detectElement($(this));
});
});
var belt;
function detectElement(arrow) {
belt = arrow.parent('.a').children('childINeedToSelect').eq(1);
belt.css("background-color", "red");
}
As you see I'm trying to send $(this) as parameter to detectElement() to determine which div was clicked. But my target div background doesn't change, and when I try to use element belt later, after it was detected by detectElement() function, Opera javascript debugger gives me error
Unhandled Error: Cannot convert 'belt.css('marginLeft')' to object
in line
var currentMargin = parseInt(belt.css('marginLeft').toString().replace('px', ''));
but this line of code worked perfectly, before calling detectElement() function; What am I doing wrong? How should I select element I need?
I'd suggest:
function detectElement(arrow) {
arrow.parent().find('.childINeedToSelect').css('background-color','red');
}
$(document).ready(function(){
$('.child').click(function(){
detectElement($(this));
});
});
JS Fiddle demo.
Or you could use the nextAll() method to find the sibling childINeedToSelect:
function detectElement(arrow) {
arrow.nextAll('.childINeedToSelect').css('background-color','red');
}
JS Fiddle demo.
And if you should have multiple .child and childINeedToSelect elements, you can pass the :first selector into the nextAll() method:
function detectElement(arrow) {
arrow.nextAll('.childINeedToSelect:first').css('background-color','red');
}
JS Fiddle demo.
I'm unsure why you were using bind(), but on the off-chance that you might be trying to account for dynamically-added elements (added after the event-handlers are bound to the various DOM nodes/jQuery objects), you could instead use on():
$('.a').on('click','.child', function(){
detectElement($(this));
});
JS Fiddle demo.
References:
find().
:first selector.
nextAll().
on().
parent().
Try this fiddle
$(document).ready(function () {
var child = $('.child');
child.bind('click', function() {
detectElement($(this));
});
});
var belt;
function detectElement(arrow) {
belt = arrow.siblings('.childINeedToSelect').eq(0);
belt.css("background-color", "red");
}
Try something like
jQuery('.a').children().first().click(function(){
jQuery('.childINeedToSelect').attr('background-color','red');
)}