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.
}
}
Related
I have the following html (it's a card) where a class is added to change the look of it:
<div class="card-small-half" id="card-1">
<a href="components/">
<div class="action-bar">
<p>Add Page</p>
<i class="material-icons">add</i>
</div>
</a>
</div>
and a switch made with a label that checks and unchecks an input type checkbox:
<div class="switch-wrapper" id="switch-wrapper-1">
<input type="checkbox" id="input-1" class="display-none">
<label class="switch" for="input-1"></label>
<p id="switch-caption-1">Visible</p>
</div>
With the following Javascript I add a class called "card-disabled" to the card:
window.onload = function () {
function check() {
if (document.getElementById("input-1").checked) {
document.getElementById("switch-caption-1").textContent = "Disabled";
$('#card-1').addClass('card-disabled');
} else {
document.getElementById("switch-caption-1").textContent = "Visible";
$('#card-1').removeClass('card-disabled');
}
}
document.getElementById('input-1').onchange = check;
check();
}
I know in css you can call id's or classes like so:
#switch-wrapper-1 input { /* styles */ }
or
#switch-wrapper-1 p { /* styles */ }
How can I do this with javascript, so I don't have to use an id for every element and instead use a global id for every wrapper.
EDIT:
The wrapper and input id's are unique! I want to call the paragraph inside the unique wrapper element something like this:
document.getElementById("switch-wrapper-1 p").textContent = "Disabled";
The 'p' here means paragraph
Is this possible and if so: how?
Query Selector is your friend here. You can use CSS selectors to retrieve DOM elements. In your case this call would return the first paragraph child in the #switch-wrapper-1 element.
var node = document.querySelector('#switch-wrapper-1 p');
If you also use jQuery, then as suggested in comments, you can simply use the $ function.
var $node = $('#switch-wrapper-1 p');
To select an individual element inside of an element with a specific ID using Javascript you can do:
document.getElementById('hello').getElementsByTagName('input')[0];
So in your example it would be:
document.getElementById('switch-wrapper-1').getElementsByTagName('input')[0].onchange = check;
The [0] is used because getElementsByTagName returns an array of all the child elements inside the parent element with the specified tag. Note that you will have to keep the unique ID on the input field if you want the for attribute on the label to function correctly.
I need a JavaScript or jQuery way of extracting the Class name of DIV element by the text it contains.
Let's illustrate. If I had let's say following code:
<div class="_className">UniqueText</div>
I need to to know how to programmatically do something like this:
getClassNameWhereText("UniqueText");
In this case output should be:
_className
Is there a way to do this?
JQuery :contains selector select element has specific text but it isn't exact. For example
$("div:contains(UniqueText)")
Select both of bottom divs
<div class="_className">UniqueText</div>
<div class="_className2">UniqueText2</div>
You can use .filter() to filter selected element by text.
var className = $("*").filter(function(){
return $(this).text() == "UniqueText";
}).attr("class");
var className = $("*").filter(function(){
return $(this).text() == "UniqueText";
}).attr("class");
console.log(className);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_className">UniqueText</div>
<div class="_className2">UniqueText2</div>
By getting all the div with each function you can search through all the divs and place a condition in which you the value of the div is equal to the particular text that you want to find. Then get the class name by using .attr('class').
$( "div" ).each(function(){
if($(this).text() == "UniqueText"){
var output = $(this).attr('class');
$(".output").html(output);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_classname">UniqueText</div>
<div class="output"></div>
It might be a bit long for a code but it gets the work done nicely. :)
You can use :contains(word)
var className = $( "div:contains('John')" ).attr("class");
console.log(className)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">John Resig</div>
<div class="bar">George Martin</div>
<div class="foo">Malcom John Sinclair</div>
<div class="baz">J. Ohn</div>
You can keep an id for your div, as per your information your text will be unique.
<div id="UniqueText" class="_className">UniqueText</div>
and the js code will be
function getClassNameWhereText(text){
var className = $('#'+text).attr('class');
console.log(className);
}
UPDATE : if you want to using contains
then you can do this,
function getClassNameWhereText(text){
var val = document.getElementById(text).value;
if(text.indexOf(val)>=0){
var className = $('#'+text).attr('class');
console.log(className);
}
}
This should be faster than using jQuery (but a bit more to type):
var xpath = "//div[text()='UniqueText']";
var result = document.evaluate(xpath,
document, null, XPathResult.FIRST_ORDERED_NODE_TYPE);
var node = result.singleNodeValue;
if (node) {
console.log(node.className);
} else {
console.error("Not found!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_className">UniqueText</div>
The reason is, browser's CSS selectors don't support :contains selector, and jQuery needs to emulate it by checking every node matching the rest of the selector. Ditto for using .filter. But XPath is done natively by the browser.
You also cannot specify exact match using the jQuery :contains, like here. If substring matching was indeed needed, you can change the XPath:
var xpath = "//div[contains(text(),'UniqueText')]";
XPath is very powerful, but a bit finicky and largely unknown, so I find it is very under-utilised, even when its use would be a perfect fit.
i have this jQuery code:
$(document).ready(function () {
$("#hide").click(function () {
$("div1").hide();
});
$("#show").click(function () {
$("div1").show();
});
});
and this jsp/html
for{int=0;i<V_loopnumber;i++)
{
%>
<button id='show' height:10px>showit</button>
<div1>
something
<button id='hide' height:10px>hideit</button>
</div1>
<%
}
For example if I have 3 elements, it produces 3 divs. However,if I push the button all the divs will be showed or hided cause they got the same name.
how can I differentiate the button with the respective divs?
Your markup has a few problems. You can not assign the same ID twice. Also div1 is not a valid tag name.
Perhaps you can restructure your markup along the lines of the following example:
<div class="container">
<button class="show">showit</button>
<div class="inner">
something
<button class="hide">hideit</button>
</div>
</div>
I assigned the buttons classes instead of ids and got rid of the div1 elements.
Now you can listen for a click event on the buttons and hide the related elements using the .closest() (http://api.jquery.com/closest/) method like this:
$(".hide").click(function () {
$(this).closest(".inner").hide();
});
$(this).closest(".inner") will retrieve the the closest element with the class inner up in the dom tree.
$(".show").click(function () {
$(this).parent().find(".inner").show();
});
$(this).parent().find(".inner") will go up one level in the dom tree and find the element with the class inner.
http://jsfiddle.net/KGk7B/
First, element ids must be unique. Use a class instead. Second, <div1> isn't a valid tag. Use a div with a class instead. Third, use traversal functions to find the specific element to toggle.
$(document).ready(function () {
$(".hide").click(function () {
$(this).closest('.show-hide-container').hide();
});
$(".show").click(function () {
$(this).next('.show-hide-container').show();
});
});
for{int=0;i<V_loopnumber;i++)
{
%>
<button class='show' height:10px>showit</button>
<div class="show-hide-container">
something
<button class='hide' height:10px>hideit</button>
</div>
<%
}
id must be unique on your page, use class
<button class='show' height:10px>showit</button>
and use $(this) in event callback function instead of using selector
$(".hide").click(function(){
$(this).parent().hide(); // this is hard select of your div1, i wrote only for your html
});
IMPORTANT: Use div instead of div1, div1 tag is undefined.
<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>
I have some markup where a lot of id's have an id attribute, as well as innerText. I want to select each of these elements, performing a function on the id.
How do I do that?
Something like this?
$('[id]:not(:empty)').each(function(i, el) {
// do stuff
});
Give them a common class:
HTML
<div id="first" class="all"></div>
<div id="second" class="all"></div>
<div id="third" class="all"></div>
jQuery
$('div.all').each(function(index){
processid(this.id);
});
If you are talking about selecting elements whose id (or some permutation of it) is included in its text then
$('[id]').filter(function(){
return $(this).text().indexOf( this.id ) >= 0; // the this.id should be altered to match the permutation you seek ..
}).css('color','red'); // turn those to red
After you comment to #lonesomeday (at the question comments) here is what to do ..
$('[id]').each(function(){
processid(this.id);
});
First select by a regular ID selector and then loop over that selection by filtering .text() non-empty.
$("[id]").each(function() {
if ($(this).text() != "") {
// do stuff
}
});