I want to insert all divs which have the class .page into an array, then call each using the array iteration. For example the array pages[] should allow me to add certain effect to the div in pages[2].
var pageDivs = document.getElementsByClassName("page");
for(i = 0; i < pageDivs.length;i++)
{
//apply your effects using pageDivs[i]
}
Do you want to do like this ?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var arr=[];
$(".page").each(function(){ arr.push($(this));});
$.each(arr,function(key,val){ val.css('color','gray')});
});
</script>
</head>
<body>
<b>.page content will be colored in gray.</b><br/><br/>
<div class="dontDo">The quick </div>
<div class="page">brown fox jumps</div>
<div class="doIt"> over the lazy dog</div>
<div class="page"> over the lazy dog</div>
</body>
</html>
I think in some of browsers getElementByClassName is not supported.However you can use calssName property like this :
function getElementsByClassName( strClassName, obj ) {
if ( obj.className == strClassName ) {
//insert this elm into array
array.push(obj);
}
}
.getElementsByClassName is not supported < IE8. If you aren't worried about that, then Sunil's response will work for you.
If you want the jQuery way:
$(".page").each(function(index) {
// do stuff here
});
Happy iterating.
Related
I'm trying change CSS class property value. I'm using this soluction:
let pizzas = document.querySelectorAll('.pizza');
pizzas.forEach( pizzaElement => pizzaElement.style.display = 'none' );
Anyone has a solution without use iteration?
It's better to use classList API with possibility to add, remove or toggle CSS classes: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
let pizzas = document.querySelectorAll('.pizza');
pizzas.forEach( pizzaElement => pizzaElement.classList.add('d-none') );
jsfiddle
EDIT:
Please describe exactly where you want to use it. If you do not want to change the property of any event it is unnecessary to do with JS. You can overwrite css or add a new class ..
if your using pure JavaScript You can use this code:
let pizzas = document.querySelectorAll('.pizza');
pizzas[0].style.display = 'none';
pizzas[1].style.display = 'none';
pizzas[2].style.display = 'none';
or if you are using JQuery you can use this:
$(document).ready(function(){
$('.pizza').css('display','none');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<DOCTYPE html>
<head>
</head>
<body>
<div class="pizza">Some Text</div>
<div class="pizza">Some Other Text</div>
<div class="pizza">Text</div>
</body>
</html>
Hi how can I extract the text of an document as an array within javascript.
It´s easy to get the innerHTML, but I do not get the text before and after the div for example.
This should be the output:
[0]=before div
[1]=innerHTML
[2]=aferHTML
[3]=before div2
[4]=innerHTML2
[5]=aferHTML2
Of the following document:
<html><head>
<body>
before div <div>innerHTML </div>aferHTML
before div2 <div>innerHTML2 </div>aferHTML2
</body></html>
I found this link, but it does not get the text before and after the elements as well:
How to get all text from all tags in one array?
You scenario is not clear. Could you please elaborate more the specific reason.
However if you want to get text from all elements in a document, kindly review this thread -> link.
By using the childNodes property you can achieve this. But for afterHtml and before div2, you need to do some extra work because they are part of the same text node.
Please take a look at the snippet below. You can remove the last element of the array manually.
const arr = [];
document.body.childNodes.forEach(node => {
arr.push(node.textContent.trim());
})
console.log(arr)
<body>
before div <div>innerHTML </div>aferHTML
before div2 <div>innerHTML2 </div>aferHTML2
</body>
Okay here's mine.
As you can see, I wrapped your HTML inside a div with a class name content.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="content">
before div <div>innerHTML </div>aferHTML
before div2 <div>innerHTML2 </div>aferHTML2
</div>
</body>
</html>
<script type="text/javascript">
var body = document.querySelector('.content').children;
var list = [];
for (var i = 0; i < body.length ; i++) {
var before = body[i].previousSibling.nodeValue.trim();
var inner = body[i].innerHTML;
var after = body[i].nextSibling.nodeValue.trim();
if (before && i == 0) list.push(before); //prevent duplication and empty value
list.push(inner);
if(after) list.push(after); //prevent empty value
}
console.log(list); //output
</script>
in innerHTML, you could split the string using inner.split(" ") if you like.
I've been working on a simple website for a while now. The basic coding and CSS are complete, so I am now looking to expand by adding certain features to the website. As it is a fully functioning website that serves a purpose, the main source of revenue comes from Google AdSense. I am looking for a way to show an image if Adblock is detected and another one if if it not.
The method I've found for detecting whether AdSense is active is shown below:
JS (saved as advertisement.js)
document.write('<div id="TestAdBlock" style="display:none;">an advertisement</div>');
The HTML bit:
<div id="adblockFrame">
<script type="text/javascript" src="js/advertisement.js"></script>
<script type="text/javascript">
if (document.getElementById("TestAdBlock") != undefined)
{
document.write('<strong>ADBlock Plus</strong> NOT detected!');
}
else
{
document.write('<strong>ADBlock Plus</strong> detected!');
}
</script>
</div>
CSS:
#adblockFrame {
visibility: hidden;
}
What I'm asking is that if someone could be kind enough to show me how, instead of displaying text, the JS would show an image in its place. I'm not that good with JS so I'm grateful for any help.
I would create an empty target div :
<div id="adblockDetector"></div>
<script type="text/javascript">
if (document.getElementById("TestAdBlock") != undefined)
{
document.getElementById('adblockDetector').innerHTML="<img src='noadblock.jpg' alt='no adblock' />";
}
else
{
document.getElementById('adblockDetector').innerHTML="<img src='adblock.jpg' alt='Adblock detected!' />";
}
</script>
Assuming you are using jquery, just because you tagged it:
html
<div id="wheretoappend"></div>
js
var whereToAppend = '#wheretoappend';
var myDiv = $('<div/>', {id: 'mydiv'});
($('#adblockFrame').length)
? myDiv.addClass('hasit').appendTo(whereToAppend)
: myDiv.addClass('doesnt').appendTo(whereToAppend);
CSS
.hasit {background: url('hasit.png');}
.doesnt {background: url('doesnt.png');}
Please, don't use the devil document.write!
If you want to add content to your page, use DOM methods or .innerHTML.
If you want to detect AdBlock, just create a global variable in advertisement.js
For example:
advertisement.js:
window.TestAdBlock = true;
Your page:
<div id="adblockFrame">
<img id="TestAdBlock" alt="AdBlock Detected???" />
<script type="text/javascript" src="js/advertisement.js"></script>
<script type="text/javascript">
(function() {
var AdBlockImg = document.getElementById('TestAdBlock');
if (window.TestAdBlock)
{
AdBlockImg.src = "/images/AdBlockDetected.jpg";
AdBlockImg.alt = "AdBlock Detected!";
}
else
{
AdBlockImg.src = "/images/AdBlockNOTDetected.jpg";
AdBlockImg.alt = "AdBlock NOT Detected!";
}
AdBlockImg.title = AdBlockImg.alt;
});
</script>
</div>
Firstly, you shouldn't use document.write for anything. It's just bad practice. But here's generally how I'd do it with jquery, since you tagged it:
<div id="adblockFrame>
<script type="text/javascript" src="js/advertisement.js"></script>
<script type="text/javascript">
var adsAllowed = adsAllowed || false;
var src = adsAllowed ? '/images/myAd.png' : '/images/noAd.png';
$('#ad').attr('src',src);
</script>
<img id="ad"/>
</div>
advertisement.js
var adsAllowed = true;
I have the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8"/>
<script type = "text/javascript" src = "js/jquery.js" ></script>
</head>
<body>
<div id = 'div'>
<div id = "1">
</div>
<div id = "2">
</div>
</div>
</body>
</html>
My JavaScript code is:
$(document).ready(function(){
var lastcommentq = document.getElementById('div').lastChild.id;
alert(lastcommentq);
});
It should alert the id of the lastchild of the div with the id 'div' which is '2' but I am getting the alert as "undefined". I don't know what I have done wrong. Please help me.
Your elements probably have text nodes around them, so the last child node of the outer <div> won't necessarily have an "id" attribute.
I'm not sure if all browsers support it, but there's a "lastElementChild" property that explicitly gets only elements, and not things like comment nodes or text nodes. Failing that, you could just loop through the node list looking for type 1 nodes.
is this your wanted behaivour?
$(document).ready(function(){
var lastchild = $("div").last().attr("id")
alert(lastchild);
});
<div id="div">
<div id ="1">
</div>
<div id="2">
</div>
</div>
check out this fiddle for live example
http://jsfiddle.net/sHgbF/
In jquery:
$(function(){
alert($("#div :last-child").attr('id'));
});
The jQuery way:
// assuming the last child is always a div
var lastcommentq = $('#div > div:last-child').attr('id');
// alternatively
var lastcommentq0 = $('#div').children('div').last().attr('id');
The JavaScript way:
var lastcommentq = document.getElementById('div').lastElementChild.id;
Note that this works in all modern browsers and IE 9+. See lastElementChild on MDN.
this is what I would have done, but I'm not clear as to if it's what you want:
$(function () {
var lastchild = $('#div div:last-child').attr('id');
alert(lastchild);
});
http://jsfiddle.net/pFjPS/
also, I don't believe classes or ids can start with numbers, so your markup is probably not valid
edit :
HTML5 supports it, but is not generally recommended.
I would use this approach, since ID is a property and not an attribute.
$(function () {
var lastchild = $('#div div:last-child').prop('id');
alert(lastchild);
});
I'm trying to check a set of divs with id='checkbox-selector-chosen' to see if a dynamic variable name exists in those divs. The code below works only if one 'checkbox-selector-chosen' div exists. What I'm trying to do is get the code below to check all of the 'checkbox-selector-chosen' divs for the existence of name.
if($(".checkbox-selector-chosen").text() == name) {
do something...
}
The structure of the divs I'm working with is as follows:
<div id="selected-results" class="group">
<div class="checkbox-selector-chosen">John</div>
<div class="checkbox-selector-chosen">Dave</div>
<div class="checkbox-selector-chosen">Jack</div>
</div>
I'm new to JS/JQuery and I'm sure this is a simple problem, but after 2 days of banging my head against my desk I've decided to ask on here.
Any help will be greatly appreciated!
You may want to use the :contains() selector to see if the item exists (JsFiddle Demo)
var name='Dave';
//Get all items that contain 'Dave'
var items = $(".checkbox-selector-chosen:contains('" + name + "')");
if (items.length > 0) {
alert(items.length + ' items found');
}
UPDATE
If you're worried about having more than one matching item, you can use my example, AND the each() function. (JsFiddle Demo). The Beauty of this approach is that you do not have to loop through all of the child divs - you only need to loop through the divs that contain the desired matching text.
var name='Dave';
//Get all items that contain 'Dave'
var items = $(".checkbox-selector-chosen:contains('" + name + "')");
if (items.length > 0) {
items.each(function(){
if ($(this).html()==name){
alert('item found!');
break;
}
});
}
UPDATE 2
Here is an example which demonstrates the full use of this technique. When you click on a name div, the name is parsed from the object that is clicked and the we use the above method to find the right div. This is, of course, not the best way to accomplish this specific task, but simple illustrates the concept. (JsFiddle Demo)
function findName(name){
var items = $(".checkbox-selector-chosen:contains('" + name + "')");
$('.checkbox-selector-chosen').css({'background':'#fff'});
if (items.length > 0) {
items.each(function(){
if ($(this).text()==name){
$(this).css({'background':'#ff0'});
}
});
}
}
$('.checkbox-selector-chosen').click(function(){
findName($(this).text());
});
Your class selector returns a collection of matches. You could try each() to iterate over them:
$(".checkbox-selector-chosen").each( function() {
if ($(this).text() == name) {
/* ..do something... */
} } );
$('.checkbox-selector-chosen').each(function(){
if($(this).text() == name) {
do something...
}
});
Maybe this is what you're looking for?
ahh beaten to it!
You can user jquery 'each' syntax for this.
$(".checkbox-selector-chosen").each(function(index, value){
console.info("index = "+index +" = "+value);
if(value == name){
console.info("match");
}
});
You want to use jQuery :contains() selector.
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title></title>
</head>
<body>
<div id="selected-results" class="group">
<div class="checkbox-selector-chosen">John</div>
<div class="checkbox-selector-chosen">Dave</div>
<div class="checkbox-selector-chosen">Jack</div>
</div>
<script type="text/javascript">
jQuery(".checkbox-selector-chosen:contains(John)").css("background-color","red")
</script>
</body>
</html>
JSBIN
You could use the contains() selector to filter the results:
$('input[type="checkbox"]').change(function(){
var checked = this.checked;
$('.checkbox-selector-chosen')
.filter(":contains("+this.value+")")
.css('color',function(){
if (checked) return "red";
else return "black";
});
});
example: http://jsfiddle.net/niklasvh/mww3J/