Want to change HTML content of a div which has a certain class but problem is there are several others and they get change too.
<div class="x"></div>
<div id="y"><div class"x">Change this</div></div>
<div class="x"></div>
I'm trying
function ReplaceContentInContainer(matchClass,content)
{
var elems = document.getElementsByTagName('*'),i;
for (i in elems)
{
if((" "+elems[i].className+" ").indexOf(" "+matchClass+" ") > -1)
{
elems[i].innerHTML = content;
}
}
}
window.onload = function ()
{
ReplaceContentInContainer("x","Success"}
but as you can guess it changes every class"x", so how can I limit this only to the class="x" which is nested in a div with id="y"?
Use jQuery
$("#y .x").html("changed it");
That is all
Related
I'm looking to try to find an element inside another element then add an ID to it as this is a multi dynamic paged Prince document, so far I have the code below but unsure of how to check if the title__container-page DIV is inside the page-first DIV, as there'as more than one page-first element, I only want to add the ID to any page-first element that contains the title__container-page element, at the moment it's adding that ID to all of them.
<script>
var checkedValue = "title__container-page";
var targetModule = document.getElementsByClassName('page-first');
var checkedArray = checkedValue.split(" ");
console.log(checkedArray);
checkedArray.forEach(function (val, key) {
if (val === "") {
checkedArray.splice(key, 1)
}
if (checkedArray.length > 0) {
targetModule[key].id = "column-padding-top";
}
})
</script>
If you want to target an element inside another element you can use queryselector.
var span = document.querySelector("#whatever .something");
span.id = "newId";
console.log(document.getElementById('newId'));
<div id=whatever>
<span class=something></span>
</div>
If you want to do it the long way you can change the context of getElementsByClassName.
var div = document.getElementById("whatever");
var span = div.getElementsByClassName("something")[0];
span.id = "newId";
console.log(document.getElementById('newId'));
<div id=whatever>
<span class=something></span>
</div>
Here are 5 parent divs with class='page-first', 3 of them containing child divs with class='title__container-page':
<div class='page-first'>
<div class='title__container-page'></div>
</div>
<div class='page-first'>
<div class='title__container-page'></div>
</div>
<div class='page-first'>
</div>
<div class='page-first'>
</div>
<div class='page-first'>
<div class='title__container-page'></div>
</div>
Inspect Element:
The following scans over all parent divs, and adds an ID to the parent found to have a child with class='title__container-page':
$('.page-first').each(function() {
this_childs = $(this).children();
this_childs.each(function() {
if($(this).attr('class') == 'title__container-page') {
add_id = 'div_' + Math.floor((Math.random() * 100000) + 1);
$(this).parent().attr('id', add_id); // add id to page-first element
}
})
})
Inspect Element:
This is assuming you can use jQuery.
Maybe this is not possible, however, i have like 50 unique divs like this:
<div id="nyc_data">
nyc
</div>
<div id="la_data">
la
</div>
<div id="san_data">
san
</div>
etc....
below is my jquery:
jQuery(document).ready(function()
{
var url=document.URL.split('#')[1];
url=url.toLowerCase();
if (url == "nyc_pics")
{
jQuery("#nyc_data").show();
jQuery("#la_data, #san_data").hide();
}
if (url == "la_pics")
{
jQuery("#la_data").show();
jQuery("#nyc_data, #san_data").hide();
}
if()
{
}
etc....
}
When this was 2 it was okay to write it out, but i can't possibly write a long jquery 50 times for each city or so. is there an efficient way to have a simple smaller jquery code?
Select all the divs first, with jQuery selector id ending with '_data' as [id$='_data'] and hide them all. This will hide your desired div as well.
Now get the desired div id from url, find it with jQuery and show.
If your uri is mySite.com/myPage#nyc_pics then var urlHash = document.URL.split('#')[1] will get "nyc_pics". After toLowercase().replace("pics", "data") this will be "nyc_data". Now, jQuery("#" + divToSHow) will be $("#nyc_data"), which will match your div. Then you can show that single div with .show()
jQuery(document).ready(function()
{
var urlHash = document.URL.split('#')[1];
var divToSHow = urlHash .toLowerCase().replace("pics", "data");
jQuery("div[id$='_data']").hide();
jQuery("#" + divToSHow).show();
});
You can use this CSS selector:
jQuery('div[id$="_data"]').show();
In your example:
jQuery(document).ready(function()
{
var url=document.URL.split('#')[1];
url=url.toLowerCase();
var currentId = '#' + url.split('_')[0] + "_data";
jQuery('div[id$="_data"]').hide();
jQuery(currentId).show();
}
It would be much easier/cleaner/faster if you just used jQuery to toggle a class on a parent element and let CSS do the work. Something like this:
window.onload = function() {
$('#all-the-things-btn').on('click', function() {
$('#my-parent-div').toggleClass('show-things');
});
};
#my-parent-div > div {
display: none;
}
#my-parent-div.show-things > div {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Toggle all the things!
<div id="my-parent-div" class="show-things">
<div id="1">stuff</div>
<div id="2">more stuff</div>
<div id="3">even more stuff</div>
</div>
I have a bunch of links in my footer and I want to link to different headings on a page and create a click event so a associated paragraph changes from display: none to display: block.
Put another way: You see headings and a footer with links (like the demo). You click the footer links and the screen should jump to (link to) an associated h2 and display a previously hidden and associated p.
Here is what I have: I can display the paragraphs when I click on the headings directly (adapted from a stackoverflow post). I can link to the headings when I click on the links in the footer. But I need to display the associated paragraph and link to a heading (both) when I click the footer links.
Here is my markup so far:
<div class="service">
<h2 class="page services"><img class="img-bullet-services" src="websiteDot.png" alt="alt">service1</h2>
<p class="p-on-white service-desc p-hide" id="service1">xxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
</div>
</br>
<div class="service">
<h2 class="page services"><img class="img-bullet-services" src="websiteDot.png" alt="alt">service2</h2>
<p class="p-on-white service-desc p-hide" id="service2">xxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
</div>
<div id="col4-footer" class="four-cols-footer four-cols">
<ul>
<li style="list-style: none;">
<h3><a class="a-bold" href="Services.php">Services</a></h3>
</li>
<li>service1
</li>
<li>seervice2
</li>
</ul>
</div>
css:
.p-hide {
display: none;
}
js:
var services = document.getElementsByClassName('service'),
servicedesc;
for (var i = 0; i < services.length; i++) {
services[i].addEventListener("click", function () {
servicedesc = this.getElementsByClassName('service-desc');
for (var j = 0; j < servicedesc.length; j++) {
servicedesc[j].classList.toggle('p-hide');
}
});
}
Demo:
http://jsfiddle.net/4GgRY/
I need the solution in vanilla JavaScript.
Hope this works
<html>
<head>
<title>internav</title>
<style type="text/css">
.hideclass{
display: none;
}
</style>
</head>
<body>
<div class="service" id="div1">
<h2 class="page services"><img class="img-bullet-services" src="websiteDot.png" alt="alt">service1</h2>
<p class="service-desc" id="service1">
xxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
</p>
</div>
</br>
<div class="service" id="div2">
<h2 class="page services"><img class="img-bullet-services" src="websiteDot.png" alt="alt">service2</h2>
<p class="service-desc" id="service2">
xxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
</p>
</div>
<div id="col4-footer" class="four-cols-footer four-cols">
<ul>
<li style="list-style: none;">
<h3><a class="a-bold" href="Services.php">Services</a></h3>
</li>
<li>service1
</li>
<li>seervice2
</li>
</ul>
</div>
<script type="text/javascript">
function toggle (link) {
target = link.getAttribute("data-toggle");
servides = document.getElementsByClassName('service-desc');//.className += " hideclass";
for (var i = servides.length - 1; i >= 0; i--) {
//servides[i].className -= " hideclass";
servides[i].className = "service-desc hideclass";
};
document.getElementById(target).className = "service-desc";
}
</script>
</body>
</html>
Hello mountainclimber,
I hope this helps you out.
If I understand your question correctly, you wish to be able to navigate to the anchors within the page and at the same time un-hide a previously hidden (or other) tag.
To that end I took your original example and developed a new version. It may not be the very best version in the world, but I think it accomplishes what you asked.
The pertinent changes are as follows.
JS:
var useQuerySelector = false;
//Shim from jscheuer1 -- http://www.dynamicdrive.com/forums/showthread.php?68847-Why-getelementsbyclassname-not-working-IE
if (!document.getElementsByClassName)
{
document.getElementsByClassName = function (cn)
{
var rx = new RegExp("(?:^|\\s)" + cn+ "(?:$|\\s)");
var allT = document.getElementsByTagName("*"), allCN = [],ac="", i = 0, a;
while (a = allT[i=i+1])
{
ac=a.className;
if ( ac && ac.indexOf(cn) !==-1)
{
if(ac===cn)
{
allCN[allCN.length] = a; continue;
}
rx.test(ac) ? (allCN[allCN.length] = a) : 0;
}
}
return allCN;
}
}
//My own feature "sniffing"
try
{
document.getElementByClassName('');
}
catch(ex)
{
useQuerySelector = true;
}
function navigateToAnchor(anchorObject)
{
var anchorName = anchorObject.href.substring(anchorObject.href.lastIndexOf("#")+1, anchorObject.href.length)
var tagObj = document.getElementById(anchorName);
var hiddenElements = (!useQuerySelector?tagObj.parentElement.getElementsByClassName("p-hide"):tagObj.parentElement.querySelectorAll(".p-hide"));
toggleElements(hiddenElements, false);
}
function toggleElements(hiddenElements, bHide)
{
var objCurrElement = null;
for (i = 0; i < hiddenElements.length; i++)
{
objCurrElement = hiddenElements[i];
if (objCurrElement != null && objCurrElement != 'undefined')
{
if (bHide)
{
//Add the p-hide class.
objCurrElement.className += "p-hide";
}
else
{
//Remove the p-hide class.
objCurrElement.className = objCurrElement.className.replace(/p\-hide/,'');
}
}
}
}
Alternatively, using a syntax I have never used before you could do it this way
JS:
function toggleElements(hiddenElements, bHide)
{
var objCurrElement = null;
for (i = 0; i < hiddenElements.length; i++)
{
objCurrElement = hiddenElements[i];
tmpObj = objCurrElement;
if (objCurrElement != null && objCurrElement != 'undefined')
{
if (bHide)
{
//Add the p-hide class.
objCurrElement.classList.add("p-hide");
}
else
{
//Remove the p-hide class.
objCurrElement.classList.remove("p-hide");
}
}
}
}
HTML:
<li>Service 1</li>
<li>Service 2</li>
That's what I have :) I have tested it clean in the latest version of FireFox and Chrome as well as IE 8 and 9.
Please let me know if it helps!
I asked the initial question and I got a good answer from g-newa, but here is an alternative (really a modification of what g-newa posted). To make it work you have to move the service1 and service2 ids up into the div:
js:
var target, sericeDiv, pToDisplay
function toggle(link) {
target = link.getAttribute("data-toggle");
sericeDiv = document.getElementById(target)
pToDisplay = sericeDiv.getElementsByTagName('p')[0]
pToDisplay.className = "p-on-white service-desc"
document.getElementById(target).className = "service-desc";
}
...seems to work. Just an alternative. Hope it helps. In words this is what it is doing: get data-toggle attribute value, use the data-toggle as an id to get the correct div, get the child p (paragraph) within the div, change the class so it is no longer includes p-hide class, move screen to the appropriate div.
If this not good in some way can you please let me know.
The complete solution INCLUDING links that work from the footer even when you AREN'T on the services page go here:
link to heading on different page and make paragraph visible from footer link while not on linked-to page
In my code, I've got 4 divs aligned inline.
What I want is, on clicking any div, it resizes to fill the space of all 4 divs (width:1000px)
and hides the other divs.
And on reclicking the div, it'll resize to the original dimensions.
This is what i've done till now.
<div class="gallery-image-replenish" id="bloc2" onclick="document.getElementById('bloc2').style.width = '980px'">
</div>
As of now, on click this resizes the div below the other divs. I know there's a method to hide the other divs, but I don't know how to do that.
With this kind of HTML:
<div class="gallery-image-replenish" id="bloc1"></div>
<div class="gallery-image-replenish" id="bloc2"></div>
<div class="gallery-image-replenish" id="bloc3"></div>
<div class="gallery-image-replenish" id="bloc4"></div>
you can use this kind of JS:
var handler = function(e){
e.target.style.width = "1000px";
for (j = divs.length; j--; ) {
if (divs[j].id != e.target.id) {
divs[j].style.display = "none";
}
}
}
var divs = document.getElementsByClassName('gallery-image-replenish'); //array of divs
var div;
for (i = divs.length; i--; ) {
div = divs[i];
div.addEventListener('click', handler);
}
Is it possible to use jQuery (jquery.com) on your project?
Because it would save a lot of code (and make it more readable!).
It would look like this (not tested, but probably works :P):
<div id="bloc1" class="gallery-image-replenish">1</div>
<div id="bloc2" class="gallery-image-replenish">2</div>
<div id="bloc3" class="gallery-image-replenish">3</div>
<div id="bloc4" class="gallery-image-replenish">4</div>
<script>
jQuery(document).ready(function(){
var galleryElements = $('.gallery-image-replenish');
galleryElements.click(function(){
var clickedElement = $(this);
if (clickedElement.hasClass('expanded')) { // if it has the class expanded, remove it (and show other elements again)
clickedElement.removeClass('expanded');
galleryElements.show();
} else { // if it has not got the expanded css class hide other and add class to expanded
galleryElements.not(clickedElement).hide(); // hide every other div
$(this).addClass('expanded'); // add stylesheet class for the new bigger width
}
});
});
</script>
The pure javascript way to hide an element is:
document.getElementById('otherdiv1').style.display = 'none';
Following is a solution which uses a common javascript function to perform what you want:-
<div class="gallery-image-replenish" id="bloc1" onclick="manageDivs(this.id)"> </div>
<div class="gallery-image-replenish" id="bloc2" onclick="manageDivs(this.id)"> </div>
<div class="gallery-image-replenish" id="bloc3" onclick="manageDivs(this.id)"> </div>
<div class="gallery-image-replenish" id="bloc4" onclick="manageDivs(this.id)"> </div>
<script type="text/javascript">
function manageDivs(divId)
{
document.getElementById(divId).style.width = '980px'";
//to hide rest of the divs
for(i=1;i<=4;i++)
{
if(divId!='bloc'+i)
document.getElementById('bloc'+i).style.display = 'none';
}
}
</script>
This is a simple exemple ,
var activ = false;
$('.aligned').live('click',function(){
if(!$(this).hasClass('actif')) {
$('.aligned').css('width','0');
$('.aligned').removeClass('actif');
$(this).css('width','1000px');
$(this).addClass('actif');
} else {
$('.aligned').css('width','250px');
}
});
you can use jQuery animate for more visual effect
I'm trying to select a specific class (in this case page1, page2, page3 etc.)
I've written this code that works fine for a single class, i've tried using .match() to exclude the .plink class picked up in dis but can't get it working.
$(function(){
$("a.plink").click(function() {
var dis = $(this).attr("class"); // This is the problem line, I need it to contain 'page1' ONLY. Not 'page1 plink'.
$("#page1,#page2,#page3").hide();
$("#" + dis).show();
return false;
});
});
The HTML that is associated with this is:
<div id="page-links">
<a class="page1 plink" href="#">About</a>
<a class="page2 plink" href="#">History</a>
<a class="page3 plink" href="#">Backstage</a>
</div>
EDIT:
These are the DIV's being shown and hidden:
<div id="page1">
<?php include_once("page1.php");?>
</div>
<div id="page2">
<?php include_once("page2.php");?>
</div>
<div id="page3">
<?php include_once("page3.php");?>
</div>
Is there a simple way to achieve this without regular expression matching?
$(function(){
var pages = $('div[id^=page]');
$("a.plink").click(function() {
var dis = $(this).attr("class").replace(' plink', '');
pages.hide().filter('#' + dis).show();
return false;
});
});
This should be
$("." + dis).show();
for class and in your example there are all classes.
As you mentioned simple way so it could be
$("a.plink").click(function() {
$(".plink").hide();
$(this).show();
return false;
});
According to your question after edit
$("a.plink").click(function() {
$('div[id^="page"]').not('#page-links').hide();
pid=$(this).attr('class').split(' ')[0];
$('#'+pid).show();
return false;
});
Here is a fiddle.
The JavaScript code is not correct. With the "#" you select ids from the html-element.
As you have only classes, the right way is to do it with "."
So this would be correct:
$(function(){
$("a.plink").click(function() {
var dis = $(this).attr("class");
$(".page1,.page2,.page3").hide();
$("." + dis).show();
return false;
});
});
I didn't test it, but I think you have to change something with the var dis.
If you click on .page1, the variable dis would contain "page1 plink".
$("." + dis).show();
would be
$(".page1 plink").show();
So I recommend to split the two classes, as it should be like
$(".page1 .plink").show();
You are trying to associate functionality of a click by appending classes. It would make more sense to put id of the div you want to show in the href
html:
<div id="page-links">
<a class="plink" href="#page1">About</a>
<a class="plink" href="#page2">History</a>
<a class=" plink" href="#page3">Backstage</a>
</div>
<div id="page1">
Content 1
</div>
<div id="page2">
Content 2
</div>
<div id="page3">
Content 3
</div>
​javascript:
jQuery(function ($) {
var pages = [];
function showPage(page) {
var i;
for(i = 0; i < pages.length; i++)
{
if(page === pages[i]) {
$(pages[i]).show();
} else {
$(pages[i]).hide();
}
}
}
// Store each href in a pages array and add handlers
$('.plink').each( function() {
var page = $(this).attr('href');
pages.push(page);
$(this).attr('href', '#');
$(this).click(function () {
showPage(page);
});
});
// show the first page
if(pages.length > 0) {
showPage(pages[0]);
}
});​
Example:
http://jsfiddle.net/38qLB/
And just so I don't avoid the actual question, which is how do you select a class from a multi class element, you should follow this example of splitting up the class name Get class list for element with jQuery if you truly insist on using classes to make your link/div association
You don't really want to exclude the plink class, because that will bring you confusion and trouble when you need to add another class. Instead you want to extract just the pageX class:
// Regex for extracting pageXX
var reg = /^(.*\s)?(page\d+)([^\d].*)?$/;
dis = reg.exec(dis)[2];
I haven't testet this 100%, but put these two lines in right after var dis = $(this).attr("class"); and you should hopefully be good to go.
i down't know if i get your question right
to get all classes with class plink u can use
var klasses $("a.plink");
now u can loop true the items
var yourClasses = Array();
for(var klass in klasses)
{
var word = klass.attr('class').replace(" plink", "");
yourClasses.push(word);
}
now you have all the classes wich have the class plink
hope this was where u where looking for
If I was just doing a minor tweak to fix your existing structure I would do something like this:
$(document).ready(function() {
$('a.plink').click(function() {
var id = $.trim(this.className.replace('plink', ''));
/*adding a "page" class to each of the page divs makes hiding the visible one a bit easier*/
$('div.page').hide();
/*otherwise use the version from sheikh*/
//$('div[id^="page"]').not('#page-links').hide();
$('div#' + id).show();
});
});
The main change I would recommend to your existing markup would be to add a common "page" class to each of the page divs. Here is a fiddle
If I was starting on this from scratch I would probably take a slightly different approach in which I define an "active" class and toggle which elements have it rather than using show/hide on the divs. And that would end up looking something like this:
Markup:
<div id="page-links">
<a class="plink active" href="#page1">About</a>
<a class="plink" href="#page2">History</a>
<a class="plink" href="#page3">Backstage</a>
</div>
<div id="page1" class='page active'> </div>
<div id="page2" class='page'> </div>
<div id="page3" class='page'> </div>
CSS:
div.page
{
height: 300px;
display:none;
}
div.page.active
{
display:block;
}
a.plink
{
padding-left:5px;
padding-right:5px;
}
a.plink.active
{
background-color:#ddd;
}
div#page1
{
background-color:blue;
}
div#page2
{
background-color:green;
}
div#page3
{
background-color:red;
}
Script:
$(document).ready(function() {
$('a.plink').click(function() {
var id = $(this).attr('href');
$('.active').removeClass('active');
$(this).addClass('active');
$('div' + id).addClass('active');
});
});
Or the fiddle here.
Oh and to answer the title question rather than just the end behavior described...
var classes = this.className.split(' ');
var id;
for (var i = 0; i < classes.length; i++) {
if(classes[i].substring(4) === classes[i].replace('page', '')) {
id = classes[i];
break;
}
}
should end up with id containing the "page#" value associated with the link that was clicked regardless of its position in the list of classes.