random div on page load - javascript

I am trying to randomize the hero content of a home page. I have this simple code, but it affects all the divs on the page, and I only want it to affect a few.
var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
}
}
Here is my html:
<div id="hero1">One</div>
<div id="hero2">Two</div>
<div id="hero3">Three</div>
<div id="constant">This content does not rotate.</div>
There is another caveat to this, I need it to work within a crappy CMS that strips out my class tags. So it has to be a solution that identifies the divs based on id.

How about
var elems = $('div').not('#constant')
?
The not function removes matching elements from the set it's called on.

Related

jQuery().detach().appendTo Duplicating all detached elements

I'm trying to add some extra divs to the build-in blogs "read more" links. I've managed to add all the necessary div but I'm struggling to move the text from where it is into another div. I've managed to move it using:
'''jQuery(".readmore").detach().appendTo('.js-add-btn-assets');'''
But instead of moving the one .readmore element to the .js-add-btn-assets. Its making copies of all of the Read More Links on the page and putting them all under the .js-add-btn-assets so I essentially have 4 .readmore elements for every Read More link.
enter image description here
How do I change this so the .readmore class is only moving to the .js-add-btn-assets within its respected parent class instead of all classes on the page?
Like this:
enter image description here
Here all the code I'm currently using
<span class="more-link">
<a href="#" class="readmore">Continue reading
<span class="screen-reader-text">Blog Template</span>
</a>
</span>
var AddButtonWrap = document.querySelectorAll(".more-link");
for (i = 0; i < AddButtonWrap.length; i++) {
AddButtonWrap[i].classList.add("dbtb-button-wrap add-dbtb-button-div");
}
var SelectButtonDiv = document.querySelectorAll(".add-dbtb-button-div"); {
for (i = 0; i < SelectButtonDiv.length; i++) {
var dbtbBtnDiv = document.createElement('div');
dbtbBtnDiv.className = 'dbtb-button js-add-btn-assets';
SelectButtonDiv[i].appendChild(dbtbBtnDiv);
}
}
jQuery(".readmore").detach().appendTo('.js-add-btn-assets');
Do the moves in a third loop.
Something like below should work (untested)
First detach, then Append.
for (i = 0; i < AddButtonWrap.length; i++)
{
var readMore = jQuery(AddButtonWrap[i]).find(".readmore").detach();
readMore.appendTo(jQuery(AddButtonWrap[i]).find(".js-add-btn-assets"));
}

removing div from html in chrome extension

I am trying to remove the following div from a page with my chrome extension
HTML (TO REMOVE)
<div class="base-popup js-base-popup"><div class="js-obscurity base-popup__obscurity"></div>
<div class="base-popup__indent"></div>
<div class="base-popup__wrap">
<div class="base-popup__container clearfix base-popup__container -decor" style="width:500px;">
<i class="s-icon -m -close base-popup__close js-close"></i>
<div class="base-popup__content js-content"><div><div class="s-text">Sample Text.
<!-- close tag -->
</p>
<!-- close tag in translate -->
</div></div></div>
</div>
Here is the JS in my content script
function removeElementsByClassName(names) {
var els = document.getElementsByClassName(names),
i, element;
for (i = els.count - 1; i > 0; i -= 1) {
element = els[i];
element.parentElement.removeChild(element);
}
}
removeElementsByClassName('base-popup js-base-popup');
getElementsByClassName only accepts a single class name, but you're giving it two. Since the HTML you've shown only has a single element that has either of the two classes you're using, if that's the only element you want to remove, just pick one:
removeElementsByClassName("base-popup");
// or
removeElementsByClassName("js-base-popup");
Alternately, you could use querySelectorAll with a CSS selector:
function removeElementsBySelector(selector) {
var els = document.querySelectorAll(selector),
i, element;
for (i = els.count - 1; i > 0; i -= 1) {
element = els[i];
element.parentElement.removeChild(element);
}
}
Then if you want to remove elements that have either class:
removeElementsBySelector('.base-popup, .js-base-popup');
Or if you only want to remove a single element that has both classes:
removeElementsBySelector('.base-popup.js-base-popup');
And as this is a Chrome extension, you can do that rather more simply with Array.from, forEach, and Element#remove:
function removeElementsBySelector(selector) {
Array.from(document.querySelectorAll(selector)).forEach(element => {
element.remove();
});
}
your javascript is completely wrong. the right way:
function removeElementsByClassName(names){
names=names.split(" ");//you just get elems by one class so you need to split it into multiple operations
for(var a=1;a<names.length;a++){//ability to remove multiple classes
removeElementsByClassName(names[a]);
}
var els = document.getElementsByClassName(names[0]);
for (var i =0; i<els.length ; i++) { // its length not count
var element = els[i];
element.parentElement.removeChild(element);
}
}
removeElementsByClassName('base-popup js-base-popup');
this removes all elements that contain one of these classes, if you wanted sth else see the other solution.

Having issue in changing style through JavaScript

Hi i am trying to change Display property of any HTML Tag with certain attribute..
But after many tries i am unable to change the tag properties.. My code is as below
function getAllElementsWithAttribute(attribute)
{
var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0; i < allElements.length; i++)
{
if (allElements[i].getAttribute(attribute))
{
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}
tags = getAllElementsWithAttribute('data-shares');
for(i=0;i<tags.length;i++)
{
tags[i].style.display = "none";
}
And the HTML has below Tag
<div class="shareTools" data-shares="facebook" data-url="#" data-title="Facebook" data-description="Facebook">
<div class="shareToolsBox">
<ul class="shareToolsList">
<li data-share="facebook">
<span>Facebook</span>
</li>
</ul>
</div>
</div>
Does anyone has any idea how to change Tag Style of any tag which has attribut i-e data-shares...
Change the function call to:
tags = getAllElementsWithAttribute('data-shares');
Here's it working on a JS Bin demo: http://jsbin.com/ufogExo/1/ The <div>s with the data-shares attribute are all hidden.
The problem was indeed the extra commas you had on your function call arguments.
I believe this does what you want:
function getAllElementsWithAttribute(attribute)
{
var items = document.querySelectorAll('['+attribute+']'),
i = items.length;
while ( i-- > 0 && (items[i].style.display = 'none') );
}
getAllElementsWithAttribute('data-shares');
see
http://jsfiddle.net/754zR/

Apply a parent to an iframe

I have fixed the video's height and width ratio using FluidVids.js. Now I want to wrap my iframe with a parent. I know that the parents working by manually throwing it inside the HTML-file. But the template I am working on needs to do this automatically.
So what I'm asking for is a (pure) JavaScript for wrapping my iframe with a div class I call fwparent. The HTML looks something like this:
<div class="post">
...
<iframe src="a-nice-video" allowFullscreen></iframe>
...
</div>
FluidVids overrides the standard sizes on the iframe. But my div class post has some paddings that I need to override with the fwparent class!
So the result should be something like this:
<div class="post">
...
<div class="fwparent"><iframe src="a-nice-video" allowFullscreen></iframe></div>
...
</div>
And remember, pure JavaScript. No extra HTTP requests for jQuery or stuff like that...
I have no experience what-so-ever with JavaScript. So be nice ;)
I have something similar which applies to images:
function imgWrap(parent) {
if (!parent || parent.nodeType !== 1) {
return false;
}
else {
var images = parent.getElementsByTagName('img'),
newDiv = document.createElement('div'),
tmp;
newDiv.className = 'parent';
for (var i = 0, len = images.length; i < len; i++) {
tmp = newDiv.cloneNode(true);
parent.insertBefore(tmp, images[i])
tmp.appendChild(images[i]);
}
}
}
imgWrap(document.querySelector('div.post'));
And jQuery does something like this:
$('iframe').wrap('<div class="fwparent" />');
But I want it to be pure JavaScript. And apply to all iframes...
Something like this?
var div = document.getElementById('wrapper').appendChild(document.createElement('div'));
div.className = 'fwparent';
div.appendChild(document.getElementById('iframe'));
EDIT
To wrap more than one iframe you need to use a loop:
var frms = document.getElementsByTagName('iframe'),
post = document.getElementById('post'),
div, n;
for (n = 0; n < frms.length; n++) {
div = post.appendChild(document.createElement('div'));
div.className = 'fwparent';
div.appendChild(frms[0]); // *
}
* = looks like we need 0 instead of n here, a live nodelist created by getElementsByTagName() is updated when appending iframes to a new location.
A live demo at jsFiddle.

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.

Categories