I have multiple elements that'll have the same data attributes but with different values, how can I get jQuery to change the value?
Below is some example HTML.
<div data-one="test" data-two="test2"></div>
<div data-one="testing" data-two="hello"></div>
<div data-one="yo" data-two="test3"></div>
By default, I would like to the value of div to be data-one but then when the class active is on the body tag, I would like it to change all the values to the data-two value.
I thought about storing values as a variable which would be easier although the divs don't have any ID's and they're scattered around in the DOM which makes it difficult.
So far I had this:
if($('body').hasClass('active')) {
$('div').html($(div).data('two'));
}
You can use html method.
var has = $('body').hasClass('active');
$('div').html(function() {
return has ? $(this).data('two') : $(this).data('one');
});
http://jsfiddle.net/44Du5/
CSS only solution:
body div:after {
content: attr(data-one);
}
body.active div:after {
content: attr(data-two);
}
http://jsfiddle.net/dfsq/gaeUR/
However it's not crossbrowser: attr function is supporter in IE8+.
Check this link: http://jsfiddle.net/rjR6q/
$(document).ready(function(){
if($('body').hasClass('active')) {
$('div').each(function(){
$(this).html($(this).data('two'));
});
}
else
{
$('div').each(function(){
$(this).html($(this).data('one'));
});
}
});
Related
According to This page I was able to remove all the CSS preloaded and added on the webpage using that. I wanted to implement a button system where "onclick" = enable/disable webpage CSS even the ones pre-loaded by my web-host. I would like to eliminate the style tags to prevent lags for my website users. I prefer using the script that I have linked above unless there is another alternative that works better. Is it possible to enable CSS onclick the same button to disable? If not is it possible, can it be done with this quick? example with the preferred script below:
if (disable) {
style = "disable";
} else {
location.reload();
}
PREFERRED SCRIPT:
function removeStyles(el) {
el.removeAttribute('style');
if(el.childNodes.length > 0) {
for(var child in el.childNodes) {
/* filter element nodes only */
if(el.childNodes[child].nodeType == 1)
removeStyles(el.childNodes[child]);
}
}
}
removeStyles(document.body);
What about a different aproach?
Add initially a class to a body called 'styled' for example
<body class="styled">
use it as a main selector in your css definitions
<style>
.styled a { ... }
.styled h1 { .... }
</style>
then an example jquery script to toggle the class:
<script>
$(function() {
$('#myswitch').click(function() {
$('body').toggleClass('styled');
});
});
</script>
when class is present, the page will be styled, when absent there will be no styling.
Of coures there could be better aproach, but this is the first thing which pops up in my mind
To remove all style on an element, you could do
function removeStyles(el) {
el.style = {};
}
If you want to enable/disable the CSS on the page, then the goal is not to merely remove all the styles on the page, but you will need to save them somewhere also so they can be recalled when the user re-clicks the button. I would recommend having jQuery to help you with this, and it could be done the following way:
var style_nodes = $('link[rel="stylesheet"], style');
style_nodes.remove();
$('*').each(function(num, obj) {
var style_string = $(obj).attr("style");
if (style_string) {
$(obj).data("style-string", style_string);
$(obj).attr("style", "");
}
});
Now you've saved the stylesheets and style DOM nodes inside of style_nodes, and the actual style attribute inside of a jQuery data attribute for that specific DOM node. When you click to add the CSS back to the page, you can do the following:
$('head').append(style_nodes);
$('*').each(function(num, obj) {
if ($(obj).data("style-string"))
$(obj).attr("style", $(obj).data("style-string"));
});
Check out this JS Fiddle I put together to demonstrate it:
https://jsfiddle.net/5krLn3w1/
Uses JQuery, but I'm sure most frameworks should give you similar functionality.
HTML:
<h1>Hello World</h1>
Turn off CSS
Turn on CSS
JS:
$(document).ready(function() {
$('a#turn_off').click(function(evt) {
evt.preventDefault();
var css = $('head').find('style[type="text/css"]').add('link[rel="stylesheet"]');
$('head').data('css', css);
css.remove();
});
$('a#turn_on').click(function(evt) {
evt.preventDefault();
var css = $('head').data('css');
console.info(css);
if (css) {
$('head').append(css);
}
});
});
CSS:
body {
color: #00F;
}
h1 {
font-size: 50px;
}
I have a list of comments built like this :
<article class="comment">
<span class="field"></span>
</article>
Inside my page some <article class="comment"> doesn't contain the
<span class="field"></span> and I need to display just the ones which have that span element.
I've tried this: jQuery('article.comment:not(:has(span.field)').hide();
Tried this also:
if (jQuery('span.field').length) {
jQuery('article.comment').show();
}
else { jQuery('article.comment').hide(); }
but this is hiding all the article.comment divs and I want to hide just the ones without the span element.
Any suggestions are welcome.
Thank you !
You are missing a parenthesis, the one closing the :not:
jQuery('article.comment:not(:has(span.field))').hide();
Fiddle : http://jsfiddle.net/qdCjP/
Try to do like this:
jQuery('article.comment').each(function() {
if(jQuery(this).find('.field').length) {
jQuery(this).show();
} else {
jQuery(this).hide();
}
});
You need to loop through the articles and hide or show each one based on the field existing -
jQuery('article.comment').each(function() {
if(jQuery(this).find('.field').length) {
jQuery(this).show();
} else {
jQuery(this).hide();
}
});
Traverse all spans and show their parents.
jQuery('article').hide();
jQuery('article span.field').each(function( i, elem){
$(elem).parent().show();
});
You can try this:
jQuery(".comment").hide();
jQuery(".comment .field").parent().show();
I am trying to delete the div when I click on it, yet I am unsure of how to go about this. Any help would be greatly appreciated.
HTML
<div onclick="fadeOut(this)"></div>
JavaScript
function fadeOut(i) {
????
}
Use:
function fadeOut(i) {
i.parentElement.removeChild(i);
}
You can use outerHTML its the inverse of innerHTML as in outerHTML pertains to only the element.
function fadeOut(i) {
i.outerHTML = ''; // deletes it from the DOM
}
And if you don't want to display it but keep it in the DOM
function fadeOut(i) {
i.style.display = 'none'; // hides the element
}
JSFIDDLE
Even you can directly do this:(If this is specific to current div.)
<div onclick="this.parentNode.removeChild(this);">xyz</div>
Using jquery you can do it as follow.
Script:
function deletediv(id) {
$("#" + id).remove();
}
html:
<div id="testdiv" style="background-color:Red; height:100px; width:100px;" onclick="deletediv(this.id)"></div>
I want to be able to remove HTML elements if they contain no content.
Let's say we have some markup and are targeting all 'collapse' classes:
<div class='collapse'>[CONTENT?]</div>
If there is some content then don't do anything.
But if there is no content - no string characters or whitespace - then remove the div element completely.
This is easy to implement in the simple cases but with nested content it's slightly more more tricky.
Here is a demo, if you try removing the [CONTENTX?] strings and then seeing what the HTML structure is you'll notice that it doesn't work completely.
If a div only has other divs with no content then that should be treated as no characters or whitespace.
If we remove all [CONTENTX?] strings then we should see no HTML structure.
What ways are there to handle this?
jsFiddle: http://jsfiddle.net/97udq/
HTML:
<div id='container'>
<div class='collapse'>
[CONTENT1?]
</div>
<div class='collapse'>
[CONTENT2?]
<div class='collapse'>
[CONTENT3?]
<div class='collapse'>[CONTENT4?]</div>
<div class='collapse'>[CONTENT5?]</div>
</div>
</div>
</div>
Javascript:
$(function(){
// function
collapse();
// Show HTML structure
alert($('#container').html());
});
function collapse(){
// Loop thru all collapse elements
$('.collapse').each(function(){
// Check for pure whitespace
if($(this).html().replace(/\s+/g, '').length==0){
// Nothing to see, so remove.
$(this).remove();
}
});
}
CSS:
.collapse{
height:20px;
border:1px solid red;
}
I think this does the job;
It just uses text() instead of html();
Here's the documentation.
This one adds the trim(), but I thik that's not what you want.
function collapse(){
$('.collapse').each(function(){
if($(this).text().length==0){
$(this).remove();
}
});
}
Here's another way of accomplishing what you want. It recurses down the DOM pruning nodes from the bottom up. Hope this helps.
function prune(root) {
$.each($(root).children(), function(){
prune($(this));
});
if($(root).html().replace(/\s+/g, '').length==0 && $(root).hasClass("collapse")){
$(root).detach();
}
}
Code integrated into your JSFiddle
You need to recreate the .each() loop, but reversed. Just like that :
function collapse(){
var el = $('.collapse');
for(var i = el.length - 1; i >= 0; i--){
if(el[i].innerHTML.replace(/\s+/g, '').length==0){
$(el[i]).remove();
}
}
}
It will remove the childrens first, then check for parent.
Here a fiddle : http://jsfiddle.net/97udq/5/
EDIT :
I missunderstood your question, here's the right solution :
function collapse(){
$('.collapse').each(function(){
var $this = $(this)
var clone = $this.clone();
clone.children().remove();
if(clone.html().replace(/\s+/g, '').length==0){
$this.children().appendTo($this.parent());
$this.remove()
}
})
}
Basicly, you clone the current div, remove its children and then check if there is some text. If there's none, you append his children to his parent
Fiddle : http://jsfiddle.net/97udq/9/
I would like to be able to look in the first span within a div with a class of t_links and buy and detect if the string Account appears. If it does then I want to set some tracking code in jQuery/JavaScript.
There will always be one span within this div. How can I search the contents for an instance of Account using jQuery?
<div class="t_links buy">
<span><a class="" href="https://www.ayrshireminis.com/account/login/">Account</a></span>
</div>
:contains is what you're looking for:
$(".t_links.buy span:first:contains('Account')")
http://api.jquery.com/contains-selector/
Edit: Added first as #adeneo pointed out. This will ensure that it's the first span that you're looking at.
Try (See Demo)
$(document).ready(function () {
if($('.t_links.buy span').text().indexOf('Account')) {
// code
}
});
Or
$(document).ready(function () {
if($(".t_links.buy span:contains('Account')").length) {
// code
}
});
Span has exact match :
if ($("span:first", ".t_links.buy").filter(function() {
return $(this).text() === 'Account';
}).length) {
//set tracking code
}
Span contains :
if ($("span:first", ".t_links.buy").filter(function() {
return $(this).text().toLowerCase().indexOf('account') != -1;
}).length) {
//set tracking code
}
If there is only one span, you can drop the :first.