Having issue in changing style through JavaScript - 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/

Related

How can set the title of all the links in a page

I would like to make some javascript code that once run adds a title of each link that is the title of the page it leads to. Sorry, all I can figure out is...
<body onload="replace()">
<script>
function replace() {
document.getElementsByTagName("a").title=this.href;
}
</script>
hi
hi2
hi3
</body>
But nothing happens and I can't figure it out.
more simple, just place correctly your script:
<body>
hi
hi2
hi3
<!-- Script for everything, just placed before </body>-->
<script>
document.querySelectorAll('a').forEach(A=>{ A.title = A.href })
</script>
</body>
getElementsByTagName returns a collection of elements, you need to use loop for setting whatever to each link.
<body onload="replace()">
<script>
function replace() {
// find all links
var links = document.getElementsByTagName("a");
// loop the collection and set title to each one
for (var i = 0; i < links.length; i++) {
links[i].title = links[i].href;
}
}
</script>
hi
hi2
hi3
</body>
Afaik, there is no way to detect a page title from a different page in JS. If you know the titles in advance, you can create a mapping object and loop over your links like so:
var map = [['link','title'],['link','title']];
$('a').each(function() {
for(var i=0; i<map.length; i++) {
if(map[i][0] == $(this).attr('src'))
$(this).attr('title', map[i][1]);
}
});
That should set all your links with the appropriate page titles based on matching the src attributes of each link against the link in your mapping object
You can use window.location.href instead of this.href. Also, you probably need to run through each link in the tag list:
function start() {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].title = window.location.href;
}
}
window.load = start();
hi
hi2
hi3
Try this answer, I have tried to add comments so that you could understand what has happened:
<a class="link" href="about.html">About</a>
<a class="link" href="careers.html">Careers</a>
<a class="link" href="contact.html">Contact</a>
<script>
//create a true array
var links = Array.from(document.getElementsByTagName("a"));
window.addEventListener(
"load", //Trigger Load event of window object
()=> //return this function
{
//links is an array of a-tag objects
for (let i = 0; i < links.length; i++)
{
//for each a tag object
//set the attribute targeted below
links[i].setAttribute
(
//target the title attribute
"title",
//set it to the current href attribute value of the that a-tag object
links[i].getAttribute("href")
);
}
}
);
</script>

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.

<li> tags are not displayed when setting the style.display = none

I'm trying to create a toggle button that can set the tags with class adsetTarget of HTML tags "li" to be hidden or visible on click event.
During page load, the state of "li" tags are hidden. This is the code that is setting the initial page load event to be hidden. This is working correctly.
var appBanners = document.getElementsByClassName('adsetTarget'), i;
for (var i = 0; i < appBanners.length; i ++) {
appBanners[i].style.display = 'none';
}
Below is the code that is trying to set toggle button functionality. On clicking first time, it is displaying the content, but on clicking it again, the content is not hiding, can someone help.
var adsetTargets = document.getElementsByClassName('adsetTarget'), i;
for (var i = 0; i < adsetTargets.length; i ++) {
if (adsetTargets[i].style.display = 'none')
adsetTargets[i].style.display = '';
else
adsetTargets[i].style.display = 'none'; //this is not working, I believe
}
You have to change the following line:
if (adsetTargets[i].style.display == 'none')
Notice the double equals?
You can use this to make it senstive to any styling you apply to your elements.
It will remember the elements previous style and re-apply it(in theory heh)
function showhide() {
var adsetTargets = document.getElementsByClassName('adsetTarget'), i;
for (var i = 0; i < adsetTargets.length; i ++) {
if (adsetTargets[i].style.display == 'none') {
adsetTargets[i].style.display = adsetTargets[i].getAttribute('data-previous');
}
else {
adsetTargets[i].setAttribute('data-previous',adsetTargets[i].style.display);
adsetTargets[i].style.display = 'none'; //this is not working, I believe
}
}
}
<ul>
<li class="adsetTarget" style="display:table">abc</li>
<li class="adsetTarget" style="display:block">123</li>
<li class="adsetTarget" style="display:inline-block">def</li>
<li class="adsetTarget" style="display:inline-block">456</li>
</ul>
<input type="button" onclick="showhide()" value="click me">

random div on page load

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.

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